基于其他几个属性的一个属性实例计数

时间:2017-10-10 21:15:04

标签: sql sql-server

Code       Date        Result    
1         6/1/17         A     
1         6/3/17         A     
2         6/5/17         A     
2         6/7/17         B     
1         6/1/17         A     
1         6/3/17         B     
1         6/5/17         C     
2         6/7/17         C

我需要编写一个查询,选择所有不同的代码,每个代码的所有实例的计数,然后根据结果计算每个代码的计数。所以最终的结果是:

Code       Total Count      Count A     Count B     Count C   
1               5              3           1           1 
2               3              1           1           1     

3 个答案:

答案 0 :(得分:0)

此查询可能适合您:

SELECT
code,
COUNT(*) AS total_count,
SUM(CASE result WHEN 'A' THEN 1 ELSE 0 END) AS count_a,
SUM(CASE result WHEN 'B' THEN 1 ELSE 0 END) AS count_b,
SUM(CASE result WHEN 'C' THEN 1 ELSE 0 END) AS count_c
FROM yourtable
GROUP BY code
ORDER BY code;

是否只有A,B和C的结果值?如果是这样,那就没关系。如果有更多的值,那么写10或20或100个案例陈述会很混乱,还有另一种方法可以做到这一点。

答案 1 :(得分:0)

如果Result已知,您可以使用上面的bbrumm答案。但是,如果有更多Result,您可以使用动态交叉表:

CREATE TABLE Tbl(Code INT, Date Date, Result VARCHAR(10));

INSERT INTO Tbl VALUES
(1, '06/01/2017',   'A'),
(1, '06/03/2017',   'A'),
(2, '06/05/2017',   'A'),
(2, '06/07/2017',   'B'),
(1, '06/01/2017',   'A'),
(1, '06/03/2017',   'B'),
(1, '06/05/2017',   'C'),
(2, '06/07/2017',   'C');

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql = 
'SELECT
    code
    , COUNT(Result) AS TotalCount' + CHAR(10);

SELECT @sql = @sql +
'   , SUM(CASE WHEN Result = ''' + Result + ''' THEN 1 ELSE 0 END) AS ' + QUOTENAME('Count' + Result) + CHAR(10)
FROM (SELECT DISTINCT Result FROM Tbl) t;

SELECT @sql = @sql +
'FROM Tbl
GROUP BY Code
ORDER BY Code';

PRINT(@sql);
EXEC sp_executesql @sql;

DROP TABLE Tbl;

ONLINE DEMO

答案 2 :(得分:0)

你可以简单地像下面一样PIVOT

select 
  Code, 
  [Total Count]=ISNULL(A,0)+ISNULL(B,0)+ISNULL(C,0),
  [Count A]=ISNULL(A,0),
  [Count B]=ISNULL(B,0),
  [Count C]=ISNULL(C,0)
from
(select * from T)src
pivot
( count(Date) for Result in (A,B,C))p

See working demo