返回0和SQL查询的时间戳

时间:2018-04-05 16:33:41

标签: sql sql-server

我有以下查询:

SELECT 
    SUM(CASE WHEN Side = 'A' THEN 1 ELSE 0 END) AS A, 
    SUM(CASE WHEN Side = 'B' THEN 1 ELSE 0 END) AS B, 
    DATEADD(DAY, 0, DATEDIFF(DAY, 0, t_stamp)) AS Time
FROM 
    Log
WHERE 
    t_stamp BETWEEN '2018-03-01 06:00:00' AND '2018-04-06 06:00:00'
    AND Bad = 1
GROUP BY 
    DATEADD(DAY, 0, DATEDIFF(DAY, 0, t_stamp)) 

但它仅返回A B不为0的天数。如下所示:

image

如何修改此查询以返回带有相应时间戳的A AND B列的0?这是我想要的输出:

image

此数据库在Microsoft SQL Server上运行,并使用JDBC驱动程序进行访问。

3 个答案:

答案 0 :(得分:0)

如果没有架构,你有点难以理解你做了什么,但是这会给你你想要的吗?

SELECT Time
FROM (
    SELECT SUM(CASE WHEN Side = 'A' THEN 1 ELSE 0 END) AS A, 
           SUM(CASE WHEN Side = 'B' THEN 1 ELSE 0 END) AS B, 
           dateadd(DAY,0, datediff(day,0, t_stamp)) as Time
    FROM Log
    WHERE t_stamp between '2018-03-01 06:00:00' AND '2018-04-06 06:00:00'
    AND Bad = 1
    GROUP BY dateadd(DAY,0, datediff(day,0, t_stamp))
) AS l
WHERE A = 1
    AND B = 1;

答案 1 :(得分:0)

在这里做一些假设......并嘲笑愚蠢的数据。这就是你要找的东西? (我认为你只需要将你的小组包括在你的小组中,你也应该将0方面包括在内)

WITH Log AS
(
    SELECT
      Side = 'A', t_stamp = '2018-03-01 06:00:00', Bad = '1'
    UNION
    SELECT
      Side = 'B', t_stamp = '2018-03-01 06:00:00', Bad = '1'
    UNION
    SELECT
      Side = 'B', t_stamp = '2018-03-01 07:00:00', Bad = '1'
    UNION
    SELECT
      Side = ' ', t_stamp = '2018-03-01 06:00:00', Bad = '1'
)
SELECT A, B, Time
FROM
(
    SELECT SUM(CASE WHEN Side = 'A' THEN 1 ELSE 0 END) AS A, 
           SUM(CASE WHEN Side = 'B' THEN 1 ELSE 0 END) AS B,
           dateadd(DAY,0, datediff(day,0, t_stamp)) as Time
    FROM Log
    WHERE t_stamp between '2018-03-01 06:00:00' AND '2018-04-06 06:00:00'
    AND Bad = 1
    GROUP BY Side, dateadd(DAY,0, datediff(day,0, t_stamp))
) a

答案 2 :(得分:0)

问题是您没有var eventNodes = document.getElementsByClassName("events"); Object.keys(eventNodes).forEach(function (key) { console.log(eventNodes[key].id); }); 所有日期的数据。一个解决方案是bad = 1,可以使用日历表或其他一些机制来生成所有日期。

更“hacky”的解决方案通常有效。如果您有所有日期的数据 - 但只是没有坏 - 那么您可以将left join条件移至where

case

或者,如果SELECT SUM(CASE WHEN Side = 'A' AND Bad = 1 THEN 1 ELSE 0 END) AS bad_A, SUM(CASE WHEN Side = 'B' AND Bad = 1 THEN 1 ELSE 0 END) AS bad_B, CAST(t_stamp as DATE) AS Time FROM Log l WHERE t_stamp BETWEEN '2018-03-01 06:00:00' AND '2018-04-06 06:00:00' GROUP BY CAST(t_stamp as DATE); ORDER BY MIN(t_stamp); 仅采用0和1的值:

bad

这并不适用于所有情况,但它通常是解决此类问题的最简单方法。