嵌套选择计数不同和分组依据

时间:2018-06-01 16:01:31

标签: sql sql-server group-by count nested

所以我试图从第3列分组的同一个表中获得2组或结果,这是我最好的例子;

SELECT
  (SELECT COUNT(DISTINCT id)
  FROM Database
    WHERE Status NOT LIKE 'closed') AS ColumnA,

  (SELECT COUNT(DISTINCT id)
  FROM Database
    WHERE Status NOT LIKE 'closed' AND Datevalue <= getdate()) AS ColumnB

Group By ColumnC

现在我知道这不会/不起作用,但它解释了我想要的东西。如果我离开小组,那么我得到的数字作为一个整体,但我希望他们按另一列分组。

心灵正在融化,准备开悟。

2 个答案:

答案 0 :(得分:2)

这是你想要的吗?

select columnC,
       count(distinct case when Status <> 'closed' then id end) as columnA,
       count(distinct case when Status <> 'closed' and datevalue <= getdate() then id end) as columnb
from database  -- a very curious name for a table
group by ColumnC;

答案 1 :(得分:0)

试试这个

    SELECT ColumnC,
    COUNT(DISTINCT CASE WHEN Status NOT LIKE 'closed' THEN id END) as  ColumnA,
    COUNT(DISTINCT CASE WHEN Status NOT LIKE 'closed' AND  Datevalue <= getdate() THEN id END) as  ColumnB
    FROM mydatabase
    GROUP BY ColumnC