SQL Server:使用count和Case

时间:2016-01-19 10:28:51

标签: sql-server

您好我们的客户已经要求"计数(值)为NAME" 现在它自己会很好很简单,但他们要求的是

3个单独的列,其中定义因子是" ID" 例如,计算值:

计数(CC所在的CC(' A',' B',' C') 加起来像这样

select case((select count(CC where CC in ('A','B','C') AB,
count(CC where CC in ('D','E') DE and id = 1234),
case((select count(CC where CC in ('Z','X','Y') XY,
count(CC where CC in ('W','G') WG and id = 1235)

任何人都可以想到这样做吗?

Sample Data
ID,  CC
1234 A
1234 B
1234 C
1234 A
1235 B
1235 B
1234 A
1235 C
1234 A
1234 B
1235 C
1234 A
1234 B
1235 B
1234 A
1235 C

预期产出

CC   ID:1234    ID:1235
A     6           0
B     3           3
C     1           1

(很抱歉,动态SQL就在这个窗口之外,客户端用来提取信息的软件不允许临时表,更新,插入或删除)

2 个答案:

答案 0 :(得分:1)

使用动态SQL:

CREATE TABLE TestTbl (ID INT,  CC VARCHAR(10));
INSERT INTO TestTbl VALUES
 (1234,'A')
,(1234,'B')
,(1234,'C')
,(1234,'A')
,(1235,'B')
,(1235,'B')
,(1234,'A')
,(1235,'C')
,(1234,'A')
,(1234,'B')
,(1235,'C')
,(1234,'A')
,(1234,'B')
,(1235,'B')
,(1234,'A')
,(1235,'C');


DECLARE @PivotColumns VARCHAR(MAX)=STUFF(
(
SELECT DISTINCT ',[ID:' + CAST(ID AS VARCHAR(MAX)) + ']'
FROM TestTbl
FOR XML PATH('')
),1,1,'');

DECLARE @SqlCmd VARCHAR(MAX)=
'
SELECT p.*
FROM
(
    SELECT DISTINCT CC
          ,COUNT(CC) OVER(PARTITION BY ID,CC) AS CountCC
          ,''ID:'' + CAST(ID AS VARCHAR(10)) AS ColumnName
    FROM TestTbl AS tbl
) AS x
PIVOT
(
    MIN(CountCC) FOR ColumnName IN(' + @PivotColumns + ')
) AS p
';


EXEC(@SqlCmd);

DROP TABLE TestTbl;

结果:

CC  ID:1234 ID:1235
A   6       NULL
B   3       3
C   1       3

答案 1 :(得分:0)

我怀疑我可能误解了你的要求,所以如果这不是你想要的答案,请接受我的道歉。

这只是根据CC和ID的组合有条件地计算行的情况吗?

示例

DECLARE @Sample TABLE
    (
        ID        INT,
        CC        VARCHAR(1)
    )
;

INSERT INTO @Sample
    (
        ID,
        CC
    )
VALUES
    (1234, 'A'),
    (1234, 'B'),
    (1234, 'C'),
    (1234, 'A'),
    (1235, 'B'),
    (1235, 'B'),
    (1234, 'A'),
    (1235, 'C'),
    (1234, 'A'),
    (1234, 'B'),
    (1235, 'C'),
    (1234, 'A'),
    (1234, 'B'),
    (1235, 'B'),
    (1234, 'A'),
    (1235, 'C')
;


SELECT
    CC,
    SUM(CASE WHEN ID = 1234 THEN 1 ELSE 0 END)        AS [ID:1234],
    SUM(CASE WHEN ID = 1235 THEN 1 ELSE 0 END)        AS [ID:1235]
FROM
    @Sample
GROUP BY
    CC
;

退回

CC  ID:1234  ID:1235
A   6        0
B   3        3
C   1        3

最后一条记录在ID中包含不同的值:1235。如果你能解释为什么这应该1我将再看看我的查询。