为另一行的每个不同条目计数具有特定条目的行

  • 本文关键字:一行 sql oracle11g
  • 更新时间 :
  • 英文 :


所以我的任务是计算一些简单的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

其他人也是如此。但我真的不知道如何将它们组合在一起,并基于第一个查询。

谢谢你的帮助。

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",然后对实例求和。我对0值做了同样的操作,对"Needs_Help"列的值1和0做了另外两个字段。我相信这会给你带来你想要的结果。

您似乎想要条件聚合:

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;

因此,如果我正确理解了这个问题,那么您只需要在Year_CW字段中查找额外两列GROUP BYSUM。这将是以下内容。

SELECT Year_CW, SUM([Is Started]), SUM([Needs Help])
FROM TestView
GROUP BY Year_CW

如果它只有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

最新更新