query SQL per unire due sottoinsiemi aggregati dalla stessa tabella
-
14-10-2019 - |
Domanda
Ho scritto una query data.stackexchange per scoprire a che ora del giorno un utente inserisce domande e risposte . Si può vedere lo SQL lì. I risultati in questo momento simile a questa:
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
Come faccio a modificare la query a:
- unire le due colonne ore in una singola colonna, e
- se domande / risposte sono
null
, insieme a0
invece.
Parte 2 è bassa priorità.
Modifica : Ecco il pieno SQL della query originale, dal momento che sto per migliorarlo in base alla risposta:
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
Soluzione
SELECT
ISNULL(q.hour, a.hour) AS hour,
ISNULL(questions,0) AS questions,
ISNULL(answers,0) AS answers
O riscrivere la query per sbarazzarsi del 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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow