汇总表格数据-分组集?其他?

时间:2020-06-25 23:55:30

标签: sql-server

我正在尝试为报告汇总多个列,而不运行多个选择。
这是一列,我想为每列显示2行(是的行和否的行)。 所需的结果是这样的:

    |Alimony |Married |HasCustody
Yes |3       |2       |4
No  |2       |3       |1

我试图做SUM(Cast IsPayingAlimony为tinyint)。我看了枢轴,不枢轴,立方体,汇总。我认为最接近的是按组分组。但是即使有分组集,我也无法进入两行。 这是我的SQL:

CREATE TABLE ClientStatus
(  ClientID INT NOT NULL,
   IsPayingAlimony BIT NOT NULL,
   IsMarried BIT NOT NULL,
   HasCustody BIT NOT NULL,
   CONSTRAINT [PK_Status] PRIMARY KEY NONCLUSTERED 
   (
    [ClientID] ASC
   )
)
;
INSERT INTO ClientStatus
(ClientID, IsPayingAlimony, IsMarried, HasCustody)
VALUES (1,0,0,0)
      ,(2,1,1,1)
      ,(3,1,0,1)
      ,(4,0,1,1)
      ,(5,1,0,1) 
;

SELECT * FROM ClientStatus

这是分组分组查询。

SELECT IsPayingAlimony, IsMarried, HasCustody, COUNT(*) AS Records
 FROM ClientStatus
GROUP BY Grouping Sets ((IsPayingAlimony), (IsMarried), (HasCustody))

这是结果。恐怕我想得太深(想不到吗?!),但是我不知道如何将其减少到两行。

IsPayingAlimony |IsMarried |HasCustody |Records
NULL            |NULL      |0          |1
NULL            |NULL      |1          |4
NULL            |0         |NULL       |3
NULL            |1         |NULL       |2
0               |NULL      |NULL       |2
1               |NULL      |NULL       |3

任何帮助或建议将不胜感激。

2 个答案:

答案 0 :(得分:0)

我在考虑values()和条件聚合:

select
    v.descr,
    sum(case when cs.IsPayingAlimony = v.val then 1 else 0 end) alimony,
    sum(case when cs.IsMarried       = v.val then 1 else 0 end) married,
    sum(case when cs.HasCustody      = v.val then 1 else 0 end) has_custody
from ClientStatus cs
cross join (values (1, 'Yes'), (0, 'No')) v(val, descr)
group by v.descr

Demo on DB Fiddle

descr | alimony | married | has_custody
:---- | ------: | ------: | ----------:
No    |       2 |       3 |           1
Yes   |       3 |       2 |           4

答案 1 :(得分:0)

发布其他答案时,我几乎完成了这项工作,分散了注意力,只是处理方法略有不同:

;WITH poss(yn, oo) AS (SELECT 'Yes',1 UNION ALL SELECT 'No',0)
SELECT poss.yn, 
  Alimony = SUM(CASE cs.IsPayingAlimony WHEN poss.oo THEN 1 ELSE 0 END),
  Married = SUM(CASE cs.IsMarried       WHEN poss.oo THEN 1 ELSE 0 END),
  Custody = SUM(CASE cs.HasCustody      WHEN poss.oo THEN 1 ELSE 0 END)
FROM poss CROSS JOIN dbo.ClientStatus AS cs
GROUP BY poss.yn;