SQL - dove condizione per ogni colonna
-
09-09-2020 - |
Domanda
Questa è una domanda Generale SQL, ma se devi sapere che il database è Firebird.
Ho questa tabella (semplificata):
user amount type -------------------- john 25 credit john 20 debit john 5 debit john 15 credit mike 15 credit.
Voglio avere un risultato che assomiglia a questo, utilizzando una singola query:
user credit debit -------------------- john 40 25 mike 15 NULL.
Where credit = SUM(amount) WHERE type=credit
and debit = SUM(amount) WHERE type=debit
.
Fondamentalmente voglio avere più campi sul risultato in base a una somma di un campo (in questo caso) ma su condizioni diverse (in questo tipo di caso).
Grazie in anticipo per qualsiasi suggerimento.
Soluzione
SQL standard sarebbe:
SELECT "user",
SUM(CASE WHEN type='credit' then amount END) as Credit,
SUM(CASE WHEN type='debit' then amount END) as Debit
FROM
"table"
GROUP BY
"user"
. Altri suggerimenti
Non sono sicuro di quanto lo faccia Firebird, ma puoi fare qualcosa come:
SELECT user,
sum(SELECT amount FROM table AS t2 WHERE t2.user = t1.user AND type="credit" ) AS credit,
sum(SELECT amount FROM table AS t3 WHERE t3.user = t1.user AND type="debit" ) AS debit
FROM table AS t1
GROUP BY user
ORDER BY user
.
Mi riferisco a quello che penso sarebbe in PostgreSQL, nel caso in cui ti aiuti a trovare ciò di cui hai bisogno.
Prova questo:
SELECT credit.user_name, credit.cre, debit.deb
FROM (SELECT user_name, SUM(amount) cre FROM t WHERE TYPE = 'credit' GROUP BY user_name) credit
LEFT OUTER JOIN (SELECT user_name, SUM(amount) deb
FROM t
WHERE TYPE = 'debit'
GROUP BY user_name) debit
ON (credit.user_name = debit.user_name)
. Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow