问题
I currently run the query:
select table1.columnA as Barrier_1,
table2.columnB as Action_1,
from table2
join table1 on table2.PrimKey = table1.PrimKey
where table1.columnA is not null
and table2.columnB is not null
group by table1.columnA, table2.columnB
order by table1.columnA
which returns the table:
Barrier_1 Action_1
____________________
01 | 01
01 | 02
02 | 01
02 | 03
02 | 04
03 | 02
03 | 03
04 | 01
05 | 04
and what I want it to do is calculate the percentage of each action per barrier:
Barrier_1 Action_1 Percent_1
________________________________
01 | 01 | 60%
01 | 02 | 40%
02 | 01 | 20%
02 | 03 | 10%
02 | 04 | 70%
03 | 02 | 20%
03 | 03 | 80%
04 | 01 | 100%
05 | 04 | 100%
Note that each action can show up multiple time per barrier.
So each barrier has it's own set of actions. For example, barrier one can have a total of 5 actions (2 being action 02 and 3 being action 01).
回答1:
There are a number of different ways to conquer this. Here is what I think is the most straight forward example:
SELECT table1.columnA as Barrier_1,
table2.columnB as Action_1,
ROUND(CAST(COUNT(*) AS FLOAT)
/CAST( (SELECT COUNT(*) FROM table2 t2
WHERE t2.PrimKey = table1.PrimKey)
AS FLOAT)*100,2) AS Percent_1
from table2
join table1 on table2.PrimKey = table1.PrimKey
where table1.columnA is not null
and table2.columnB is not null
group by table1.columnA, table2.columnB
order by table1.columnA
If you want to add the percentage symbol you will have to convert to varchar at the end.
Note: I am converting to float type in the example, if you require a high degree of accuracy in the numbers, it is better to use a numeric/decimal type
回答2:
You can use a sub-query for getting sum of all Actions
for one Barrier
. And then calculate percentage of Actions
for one Barrier
.
SELECT b.ColumnA
, a.ColumnB
, ROUND(CONVERT(DECIMAL(19,4),
COUNT(a.ColumnB))* 100/
CONVERT(DECIMAL(19,4),
(SELECT COUNT(ColumnB) FROM Action WHERE PrimKey=b.PrimKey))
, 2) AS Pros
FROM Action a
INNER JOIN Barrier b ON b.PrimKey=a.PrimKey
GROUP BY b.ColumnA, a.ColumnB, b.PrimKey
ORDER BY b.ColumnA
Here a link to SQL Fiddle with data which I used for testing...
If your want to add a '%'-sign to result column, then you need to convert value of percentage to VARCHAR
and add a sign.
CONVERT(VARCHAR(20), @PercentageValue) + '%' AS PercentageValue
来源:https://stackoverflow.com/questions/16819768/calculating-a-percentage-based-on-results-from-the-query