结合几个查询

时间:2016-03-15 12:32:06

标签: sql sql-server sql-server-2008

我写了4个查询, 所有这些都显示了一个列的详细信息,即[来源]

我需要将这些查询组合在一起,因此结果将是Shawn在一个表中,每个[Source]都有所有结果(如1表中包含所有结果,没有重复参数)

非常感谢。  查询:

1)

SELECT  [Source] ,
        COUNT (DISTINCT ROW_ID ) AS 'Number Of Contacts'
FROM [SRL-TST].[dbo].[TBL_SRL_Contacts]
GROUP BY [Source]

2)

SELECT [Source] , 
       COUNT (DISTINCT ROW_ID ) AS 'FULL'
FROM dbo.TBL_SRL_Contacts
WHERE Email IS NOT NULL 
AND Company IS NOT NULL
AND Privetphone IS NOT NULL
AND Secondphone IS NOT NULL
GROUP BY [Source]

3)

SELECT [Source] , 
       COUNT (DISTINCT ROW_ID ) AS 'PARTLY'
FROM dbo.TBL_SRL_Contacts
WHERE Email IS NOT NULL 
OR Company IS NOT NULL
OR Privetphone IS NOT NULL
OR Secondphone IS NOT NULL

GROUP BY [来源]

4)

SELECT [Source] , 
       COUNT(DISTINCT ROW_ID ) AS 'MISSING'
FROM dbo.TBL_SRL_Contacts
WHERE Email IS  NULL 
AND Company IS  NULL
AND Privetphone IS  NULL
AND Secondphone IS  NULL
GROUP BY [Source]

1 个答案:

答案 0 :(得分:3)

您可以使用条件聚合:

SELECT [Source] ,
       COUNT(DISTINCT ROW_ID ) AS [Number Of Contacts],
       COUNT(DISTINCT CASE WHEN Email IS NOT NULL AND Company IS NOT NULL AND Privetphone IS NOT NULL AND Secondphone IS NOT NULL
                  THEN ROW_ID
             END) as [Full],
       COUNT(DISTINCT CASE WHEN Email IS NOT NULL OR Company IS NOT NULL OR Privetphone IS NOT NULL OR Secondphone IS NOT NULL
                  THEN ROW_ID
             END) as [Partly]
       COUNT(DISTINCT CASE WHEN Email IS  NULL AND Company IS  NULL AND Privetphone IS  NULL AND Secondphone IS  NULL
                  THEN ROW_ID
             END) as [Missing]
FROM [SRL-TST].[dbo].[TBL_SRL_Contacts]
GROUP BY [Source];