【问题标题】:SQL query to merge two aggregated subsets from the same table用于合并来自同一个表的两个聚合子集的 SQL 查询
【发布时间】:2011-06-02 03:08:27
【问题描述】:

我写了一个 data.stackexchange 查询来找出what hour of the day a user posts questions and answers。您可以在那里看到 SQL。现在的结果如下所示:

hour hour questions answers 
---- ---- --------- ------- 
0    0    1         4       
null 2    null      4       
null 3    null      5       
null 4    null      7       
null 5    null      11      
null 6    null      10      
null 7    null      6       
null 8    null      1       
null 13   null      1       
null 14   null      7       
null 15   null      8       
null 16   null      11      
null 17   null      4       
null 18   null      10      
null 19   null      4       
null 20   null      6       
null 21   null      7       
22   22   1         6       
null 23   null      2     

如何将查询修改为:

  1. 将两个小时列合并为一个列,然后
  2. 如果问题/答案是 null,请改为设置为 0

第 2 部分的优先级较低。

编辑:这是原始查询的完整 SQL,因为我将根据答案对其进行改进:

SELECT
   q.hour, a.hour, questions, answers
FROM
(
   SELECT
     datepart(hour,creationdate) AS hour,
     count(*) AS questions
   FROM posts
   WHERE posttypeid=1 AND OwnerUserId=##UserID##
   GROUP BY datepart(hour,creationdate)
) q
FULL JOIN 
(
   SELECT
     datepart(hour,creationdate) AS hour,
     count(*) AS answers
   FROM posts
   WHERE posttypeid=2 AND OwnerUserId=##UserID##
   GROUP BY datepart(hour,creationdate)
) a
ON q.hour = a.hour
ORDER BY a.hour, q.hour

【问题讨论】:

    标签: sql-server tsql dataexplorer


    【解决方案1】:
    SELECT
       ISNULL(q.hour, a.hour) AS hour, 
       ISNULL(questions,0) AS questions, 
       ISNULL(answers,0) AS answers
    

    或者重写查询以去掉full join

       SELECT
         datepart(hour,creationdate) AS hour,
         count(CASE WHEN posttypeid = 1 THEN 1 END) AS questions,
         count(CASE WHEN posttypeid = 2 THEN 1 END) AS answers
       FROM posts
       WHERE posttypeid IN (1,2) AND OwnerUserId=##UserID##
       GROUP BY datepart(hour,creationdate)
    

    【讨论】:

    • 很好地使用CASE!我打算单独接受您对第一部分的回答,但第二部分更好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 2017-08-22
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2020-01-10
    • 2014-02-23
    相关资源
    最近更新 更多