1

我编写了一个 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
4

1 回答 1

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)
于 2010-12-31T22:02:59.233 回答