所以我的任务是计算一些简单的KPI。
我已经积累了需要的所有数据的视图。
Year_CW Is Started Needs Help
-------------------------------------
2018/45 0 1
2018/43 1 1
2018/45 0 1
2018/42 1 0
2018/45 0 1
2018/45 1 1
2018/41 0 1
2018/43 0 0
2018/45 1 1
2018/45 0 0
然后我写了以下查询:
SELECT DISTINCT YEAR_CW
FROM TestView
ORDER BY YEAR_CW DESC
哪个返回此
Year_CW
--------
2018/45
2018/44
2018/43
2018/42
我现在想为Year_CW的每行计数一次,其他两行分别为1和0。这可能是一个非常简单的问题,但是我只是从SQL开始,我真的不知道基于外部查询的查询的关键字是什么。
其他查询将是
Select Count(Is Started)
from Testview
Where Is Started = 1
以此类推。但是我真的不知道如何将它们放在一起并基于第一个查询。
感谢您的帮助。
答案 0 :(得分:1)
您似乎想要条件聚合:
select Year_CW,
sum(case when col = 1 then 1 else 0 end) as one_count,
sum(case when col = 0 then 1 else 0 end) as zero_count
from (select Year_CW, IsStarted as col
from TestView tv
union all
select Year_CW, NeedsHelp
from TestView tv
) tv
group by Year_CW
order by Year_CW desc;
答案 1 :(得分:1)
select Year_CW
, sum(case when Is_Started = 1 then 1 end) as Is_Started_1
, sum(case when Is_Started = 0 then 1 end) as Is_Started_0
, sum(case when Needs_Help = 1 then 1 end) as Needs_Help_1
, sum(case when Needs_Help = 0 then 1 end) as Needs_Help_0
from Test_View
group by Year_CW
所以我是怎么做的,我为您创建了4个新字段。首先是为“ Is_Started = 1”的每个字段赋予值“ 1”,然后对这些实例求和。对于“ Needs_Help”列,我对0值做了同样的处理,对值1和0做了另外两个字段。我相信这会给您您想要的结果。
答案 2 :(得分:0)
因此,如果我对问题的理解正确,那么您只是在寻找Year_CW字段的另外两列SUM
中的GROUP BY
。就是这样。
SELECT Year_CW, SUM([Is Started]), SUM([Needs Help])
FROM TestView
GROUP BY Year_CW
答案 3 :(得分:0)
如果只有0或1,则可以将0或1加起来。
SELECT YEAR_CW,
SUM("Is Started") AS TotalStarted,
SUM(1 - "Is Started") AS TotalNotStarted,
SUM("Needs Help") AS TotalNeedsHelp,
SUM(1 - "Needs Help") AS TotalNoHelpNeeded
FROM TestView
GROUP BY YEAR_CW
ORDER BY YEAR_CW DESC