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. 両方の時間列を 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 に答える