如何组合两个具有不同where子句和Group的查询由不同的Date列组成

时间:2017-06-28 07:23:35

标签: sql sql-server-2008

尝试以多种方式结束错误。 我有两个查询如下:

SELECT EnqDate AS Date, COUNT(ID) AS EnqueryCount
FROM Enquiry 
 WHERE EnqDate BETWEEN 'June 24 2017' AND 'June 29 2017'
 GROUP BY EnqDate
order by Date

SELECT FirstTryDateTime AS Date, COUNT(ID) AS FirstCallCount
FROM Enquiry 
 WHERE FirstTryDateTime BETWEEN 'June 24 2017' AND 'June 29 2017'
 GROUP BY FirstTryDateTime
order by Date

给出了以下结果:

enter image description here

我需要结合这两个查询并需要如下结果:

enter image description here

请有人帮我吗?

4 个答案:

答案 0 :(得分:0)

我只想通过Date:

列加入两个查询结果
SELECT A.Date
      ,A.EnqueryCount
      ,B.FirstCallCount
  FROM
    (
    SELECT EnqDate AS Date, COUNT(ID) AS EnqueryCount
    FROM Enquiry 
     WHERE EnqDate BETWEEN 'June 24 2017' AND 'June 29 2017'
     GROUP BY EnqDate
    order by Date
    ) A
LEFT JOIN
    (
    SELECT FirstTryDateTime AS Date, COUNT(ID) AS FirstCallCount
    FROM Enquiry 
     WHERE FirstTryDateTime BETWEEN 'June 24 2017' AND 'June 29 2017'
     GROUP BY FirstTryDateTime
    order by Date
    ) B
  ON A.Date = B.Date

答案 1 :(得分:0)

WITH enquery AS (
SELECT EnqDate AS Date, COUNT(ID) AS EnqueryCount
FROM Enquiry 
GROUP BY EnqDate
) 
SELECT Date, EnqueryCount, COUNT(ID) AS FirstCallCount
FROM Enquiry 
JOIN enquery ON Date = FirstTryDateTime
WHERE Date BETWEEN 'June 24 2017' AND 'June 29 2017'
AND FirstTryDateTime BETWEEN 'June 24 2017' AND 'June 29 2017'
GROUP BY Date, EnqueryCount
ORDER BY Date

旁注,您应该尽量避免使用Oracle保留字(即日期)作为列名。

答案 2 :(得分:0)

您可以使用UNPIVOT取消忽略该表,然后应用条件聚合以获得所需的结果:

SELECT Val,
       COUNT(CASE WHEN DateField = 'EnqDate' THEN ID END) AS EnqueryCount, 
       COUNT(CASE WHEN DateField = 'FirstTryDateTime' THEN ID END) AS FirstCallCount
FROM (
   SELECT ID, EnqDate, FirstTryDateTime
   FROM Enquiry
   WHERE (EnqDate BETWEEN '2017-06-24' AND '2017-06-29') OR
         (FirstTryDateTime BETWEEN '2017-06-24' AND '2017-06-29')) AS p
UNPIVOT (Val FOR DateField IN ( EnqDate, FirstTryDateTime)) AS unpvt
GROUP BY Val
ORDER BY Val

答案 3 :(得分:0)

只需将Union AllSum()Subquery组合在一起

SELECT Sel.Date, sum(EnqueryCount) as EnqueryCount, sum(FirstCallCount) as FirstCallCount  
FROM
    (SELECT EnqDate AS Date, 1 AS EnqueryCount, 0 AS FirstCallCount
    FROM Enquiry 
     WHERE EnqDate BETWEEN 'June 24 2017' AND 'June 29 2017'
    union all
    SELECT FirstTryDateTime AS Date, 0 AS EnqueryCount, 1 AS FirstCallCount
    FROM Enquiry 
     WHERE FirstTryDateTime BETWEEN 'June 24 2017' AND 'June 29 2017') Sel
group by Sel.Date
order by Sel.Date