将SQL查询组合到一个查询中

时间:2015-04-08 10:40:38

标签: sql sql-server

您好我有一组获取数据的查询

当天有两个计数行,晚上有两个计数行,我想要的是将这些行合并到一个查询中。

SELECT controllerID
    ,COUNT(CardID) AS GoodCountDay
FROM ReaderData
WHERE (
        ReaderTime BETWEEN '08:00:00'
            AND '20:00:00'
        )
    AND (CardID = 'fffffff0')
    AND (DATEDIFF(DAY, DATEADD(DAY, - 0, CURRENT_TIMESTAMP), dtReading) = 0)
GROUP BY controllerID

SELECT controllerID
    ,COUNT(CardID) AS ScrapCountDay
FROM ReaderData
WHERE (
        ReaderTime BETWEEN '08:00:00'
            AND '20:00:00'
        )
    AND (CardID = '007CF00B')
    AND (DATEDIFF(DAY, DATEADD(DAY, - 0, CURRENT_TIMESTAMP), dtReading) = 0)
GROUP BY controllerID

SELECT controllerID
    ,COUNT(CardID) AS GoodCountNight
FROM ReaderData
WHERE (dtReading >= DATEADD(hour, 20, DATEADD(day, - 1, CAST(CAST(GETDATE() AS DATE) AS DATETIME))))
    AND (dtReading < DATEADD(hour, 8, CAST(CAST(GETDATE() AS DATE) AS DATETIME)))
GROUP BY controllerID

SELECT controllerID
    ,count(CardID) AS ScrapCountNight
FROM ReaderData
WHERE dtReading >= dateadd(hour, 20, dateadd(day, - 1, cast(cast(getdate() AS DATE) AS DATETIME)))
    AND dtReading < dateadd(hour, 8, cast(cast(getdate() AS DATE) AS DATETIME))
    AND (CardID = '007CF00B')
GROUP BY controllerID

所有这些查询都有相同的输出,看起来像这样

 controllerID   GoodCountDay
            2   207
            28  245
            30  267
            33  314
            35  471
            37  65
            38  17
            40  175

有什么方法可以将这些结合到一个查询中,所以输出就是这样

 controllerID GoodCountDay  ScrapCountDay  GoodCountNight  ScrapCountNight
      2           207              12             123              1
      28          245              123
      30          267         
      33          314
      35          471
      37          65
      38          17
      40         175

1 个答案:

答案 0 :(得分:7)

您可以使用条件聚合:

SELECT controllerID,
       SUM(CASE WHEN ReaderTime BETWEEN '08:00:00' AND '20:00:00' AND
                     DATEDIFF(DAY, DATEADD(DAY, - 0, CURRENT_TIMESTAMP), dtReading) = 0) AND
                     CardID = 'fffffff0' THEN 1 ELSE 0 END) as GoodCountDay
       SUM(CASE WHEN ReaderTime BETWEEN '08:00:00' AND '20:00:00' AND
                     DATEDIFF(DAY, DATEADD(DAY, - 0, CURRENT_TIMESTAMP), dtReading) = 0) AND
                     CardID = '007CF00B' THEN 1 ELSE 0 END) as ScrapCountDay,
       SUM(CASE WHEN dtReading >= DATEADD(hour, 20, DATEADD(day, - 1, CAST(CAST(GETDATE() AS date) AS datetime)))) AND
                     (dtReading < DATEADD(hour, 8, CAST(CAST(GETDATE() AS date) AS datetime)) AND
                     CardID = 'fffffff0' THEN 1 ELSE 0 END) as GoodCountNight
       SUM(CASE WHEN dtReading >= DATEADD(hour, 20, DATEADD(day, - 1, CAST(CAST(GETDATE() AS date) AS datetime)))) AND
                     (dtReading < DATEADD(hour, 8, CAST(CAST(GETDATE() AS date) AS datetime)) AND
                     CardID = '007CF00B' THEN 1 ELSE 0 END) as ScrapCountNight
FROM   ReaderData
group by controllerID;