独特的计数 - TSQL

时间:2016-08-17 15:43:24

标签: sql tsql sql-server-2012

CODE

CREATE TABLE #TEMP (ID INT, AVAIL BIT, FK INT, DT DATETIME);
INSERT INTO #TEMP (ID,AVAIL,FK,DT)
SELECT 1,1,1,GETDATE()
UNION ALL
SELECT 2,0,2,GETDATE()
UNION ALL
SELECT 3,1,3,GETDATE()
UNION ALL
SELECT 1,1,4,GETDATE()
UNION ALL
SELECT 4,0,5,GETDATE()
UNION ALL
SELECT 5,1,6,GETDATE();


CREATE TABLE #FK (FK INT, DT2 DATETIME)
INSERT INTO #FK (FK, DT2)
SELECT 1,NULL
UNION
SELECT 2,DATEADD(DAY,1,GETDATE())
UNION
SELECT 3,DATEADD(DAY,1,GETDATE())
UNION
SELECT 4,NULL
UNION
SELECT 5,NULL
UNION
SELECT 6,DATEADD(DAY,1,GETDATE())
UNION
SELECT 7,DATEADD(DAY,1,GETDATE())


SELECT 
[TotalIds] = COUNT(DISTINCT ID)
,[TotalAvail] = SUM(CASE WHEN [AVAIL] = 1 THEN 1 ELSE 0 END)
,[DTDIFF] = SUM(DATEDIFF(DAY,T1.DT,F.DT2))
FROM #TEMP T1 INNER JOIN #FK F
    ON T1.FK = F.FK;

DROP TABLE #TEMP;
DROP TABLE #FK;

输出

TotalIds    TotalAvail  DTDIFF
5           4           3

期望的输出

TotalIds    TotalAvail  DTDIFF
5           3           3

目标:
我想得到sum/count of UNIQUE IDs where [AVAIL] = 1.

我可以通过COUNT(DISTINCT ID) WHERE [AVAIL] = 1做到这一点但是......我需要在此SUM中执行此操作,因为我在查询同一查询中的其他数据。

 Desired output = 3 
(for ID 1, 3, and 5).

更新了当前/所需的输出。 更新了更多数据。

3 个答案:

答案 0 :(得分:3)

您可以更改UNION的{​​{1}} ALL并删除重复项

但是你提到了其他值,所以也许你需要这样的东西

UNION

答案 1 :(得分:2)

CREATE TABLE #TEMP (ID INT, AVAIL BIT, FK INT, DT DATETIME);
INSERT INTO #TEMP (ID,AVAIL,FK,DT)
SELECT 1,1,1,GETDATE()
UNION ALL
SELECT 2,0,2,GETDATE()
UNION ALL
SELECT 3,1,3,GETDATE()
UNION ALL
SELECT 1,1,4,GETDATE()
UNION ALL
SELECT 4,0,5,GETDATE()
UNION ALL
SELECT 5,1,6,GETDATE();


CREATE TABLE #FK (FK INT, DT2 DATETIME)
INSERT INTO #FK (FK, DT2)
SELECT 1,NULL
UNION
SELECT 2,DATEADD(DAY,1,GETDATE())
UNION
SELECT 3,DATEADD(DAY,1,GETDATE())
UNION
SELECT 4,NULL
UNION
SELECT 5,NULL
UNION
SELECT 6,DATEADD(DAY,1,GETDATE())
UNION
SELECT 7,DATEADD(DAY,1,GETDATE())


SELECT 
[TotalIds] = COUNT(DISTINCT ID)
,[TotalAvail] = COUNT(DISTINCT CASE WHEN [AVAIL] = 1 THEN ID ELSE NULL END)
,[DTDIFF] = SUM(DATEDIFF(DAY,T1.DT,F.DT2))
FROM #TEMP T1 INNER JOIN #FK F
    ON T1.FK = F.FK;


DROP TABLE #TEMP;
DROP TABLE #FK;

答案 2 :(得分:1)

使用cte结果进行进一步处理。

;WITH CTE_Temp AS
(SELECT COUNT(DISTINCT ID) [TotalAvail] 
 FROM  #TEMP
 WHERE [Avail]=1)
 SELECT [TotalAvail]
 FROM CTE_Temp