我写了一个data.stackexchange查询以查找 用户每天几个小时发布问题和答案. 。您可以在那里看到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
有帮助吗?

解决方案

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top