我有一个数据表,请参见http://sqlfiddle.com/#!4/cf72da/5 使用枢轴语句,我可以按标题细分计数
select division, status,
sum(case when title = 'worker' then 1 else 0 end) as workerCount,
(sum(case when title = 'worker' then 1 else 0 end) /
sum(sum(case when title = 'worker' then 1 else 0 end)) over ()
)*100 as workerPercent
from ta
group by status, division
order by division, status
所以结果看起来像这样:
DIVISION STATUS WORKERCOUNT WORKERPERCENT
11 ready 3 30
11 started 3 30
12 finished 4 40
12 ready 0 0
12 started 0 0
例如,我实际上需要将百分比除以除法
DIVISION STATUS WORKERCOUNT WORKERPERCENT
11 ready 3 50
11 started 3 50
12 finished 4 100
12 ready 0 0
12 started 0 0
有什么想法可以用SQL完成吗?
答案 0 :(得分:0)
使用以下查询:
select division, status,
sum(case when title = 'worker' then 1 else 0 end) as workerCount,
(sum(case when title = 'worker' then 1 else 0 end) /
sum(sum(case when title = 'worker' then 1 else 0 end)) over (PARTITION BY division)
)*100 as workerPercent
from ta
group by status, division
order by division, status
答案 1 :(得分:0)
您缺少分析子句:
state = state % 3 + 1
答案 2 :(得分:0)
您非常接近预期的结果。
您只需要在partition by
中添加analytical function
子句,如下所示:
SQL> SELECT 2 DIVISION, 3 STATUS, 4 SUM(CASE WHEN TITLE = 'worker' THEN 1 ELSE 0 END) AS WORKERCOUNT, 5 ( SUM(CASE WHEN TITLE = 'worker' THEN 1 ELSE 0 END) / 6 SUM(SUM(CASE WHEN TITLE = 'worker' THEN 1 ELSE 0 END)) 7 OVER( PARTITION BY DIVISION ) -- Changes here 8 ) * 100 AS WORKERPERCENT 9 FROM TA 10 GROUP BY STATUS, DIVISION 11 ORDER BY DIVISION, STATUS; DIVISION STATUS WORKERCOUNT WORKERPERCENT ---------- -------------------- ----------- ------------- 11 ready 3 50 11 started 3 50 12 finished 4 100 12 ready 0 0 12 started 0 0 SQL>
干杯!
答案 3 :(得分:0)
正如其他张贴者所指出的那样,您可以(并且应该)使用解析函数来解决此类问题。
专门针对您的用例,提供了RATIO_TO_REPORT
函数-比您尝试和在几个答案中“手动”计算事物要好得多。
请注意我所做的另一项更改-当“ worker”和1“ 0”等于0时,总和为1。在这种情况下,COUNT
比SUM
更清晰。
select division, status,
count(case when title = 'worker' then 1 end) as workerCount,
ratio_to_report(count(case when title = 'worker' then 1 end))
over (partition by division)*100 as workerPercent
from ta
group by status, division
order by division, status;
感谢您发布测试数据和您的尝试-这非常有帮助!