加入/ UNION ALL以在不同的列中显示结果

时间:2016-02-20 07:23:27

标签: sql-server

我根据某些条件从3个不同的表中获取COUNT,但是按时间间隔对它们进行分组。 (比如:1小时30分钟。)

我需要以下输出:

Date            Interval    Success Un-Success  Closed  CLInotFound
2/20/2016   01:01 – 02:00   5          3           2    13
2/20/2016   02:01 – 03:00   14         9          23    5
2/20/2016   03:01 – 04:00   8         67          89    345
2/20/2016   04:01 – 05:00   2         23          92    12
2/20/2016   05:01 – 06:00   44        55          78    98
2/20/2016   06:01 – 07:00   12        87          56    445

我可以单独计算它们,但是当我尝试组合时,结果会有所不同。

查询1获得成功&未成功:

SELECT CONVERT(VARCHAR(5), A.InsertionDate ,108) AS 'Interval',
    COUNT(CASE WHEN A.call_result = 0 then 1 ELSE NULL END) AS 'Success',
    COUNT(CASE WHEN A.call_result = 1 then 1 ELSE NULL END) AS 'Un-Success'
from dbo.AutoRectifier A 
WHERE CONVERT(DateTime,A.InsertionDate,101) BETWEEN '2016-02-19 02:10:35.000' AND '2016-02-19 07:15:35.000'
GROUP BY A.InsertionDate; 

查询2已结束:

SELECT CONVERT(VARCHAR(5), C.DateAdded ,108) AS 'Interval',
 COUNT(*) AS 'Closed' FROM dbo.ChangeTicketState C 
WHERE C.SourceFlag = 'S-CNR' AND C.RET LIKE '%CLOSE%' 
AND C.DateAdded BETWEEN '2016-02-19 02:10:35.000' AND '2016-02-19 07:15:35.000'
GROUP BY C.DateAdded;

查询3未找到CLI:

SELECT CONVERT(VARCHAR(5), T.DateAdded ,108) AS 'Interval',
        COUNT(*) 'CLI Not Found' FROM dbo.TICKET_INFO T
     WHERE T.CONTACT_NUMBER = '' AND T.DateAdded BETWEEN '2016-02-19 02:10:35.000' AND '2016-02-19 07:15:35.000'
     GROUP BY T.DateAdded;

1 个答案:

答案 0 :(得分:1)

你有几个问题需要解决。

  1. 您必须从Query1,Query2,Query3生成联合结果集以对其进行分组。您可以使用UNION ALL,但所有3个查询都必须具有相似的列列表。所以,添加
    0 as Closed, 0 as CLInotFound
    选择Query1的列表, 添加
    0 as Success, 0 as Un-Success, 0 as CLInotFound
    选择Query2的列表并添加
    0 as Success, 0 as Un-Success, 0 as Closed
    到Query3 然后你可以写
    select * from Query1 union all select * from Query2 union all select * from Query3

  2. 不要在Query1,Query2,Query3上将日期转换为varchar。更好地从查询返回日期时间,以便在联合后使用它进行分组。因此,查询1看起来像是 SELECT A.InsertionDate AS Date, ...
    查询2 -
    SELECT C.DateAdded AS Date, ...
    等。

  3. 然后,您可以按小时对结果进行分组,例如使用GROUP BY SUBSTRING(CONVERT(VARCHAR(20), Date ,120), 1, 13)

  4. 所以,结果看起来像是     SELECT SUBSTRING(CONVERT(VARCHAR(20), Date ,120), 1, 13) as Interval, sum(Success) as sum(Un-Success) as, sum(Closed) as, sum(CLInotFound) as from ( select * from Query1 union all select * from Query2 union all select * from Query3 ) q GROUP BY SUBSTRING(CONVERT(VARCHAR(20), Date ,120), 1, 13)

    其结果与Date和Interval字段的格式略有不同,但显示了这个想法。 您可以使用GROUP BY DATEPART(yy, Date), DATEPART(mm, Date), DATEPART(dd, Date), DATEPART(hh, Date)代替GROUP BY SUBSTRING(CONVERT(VARCHAR(20), Date ,120), 1, 13),并根据需要进行格式化。

    结果集也不包含原始数据中不存在的间隔。 您可以添加Query4,其中包含所有必需的间隔,并在所有字段中使用零来修复它。