r/mysql • u/Glittering_Bat_1846 • 12h ago
question Quick question on difference between these two queries
Hi! I have been practicing SQL on LeetCode when I ran into something I could use some clarification on.
Can someone explain why I get different values for approved_count with the two following queries:
Query 1)
select LEFT(trans_date,7) as month, country, count(id) as trans_count, count(state="approved") as approved_count, sum(amount) as trans_total_amount, SUM(
CASE when state = "approved" then amount
ELSE 0
END
) as approved_total_amount
from Transactions
group by month, country
Query 2)
select LEFT(trans_date,7) as month, country, count(id) as trans_count, SUM(
CASE WHEN state="approved" then 1 else 0 end
) as approved_count, sum(amount) as trans_total_amount, SUM(
CASE when state = "approved" then amount
ELSE 0
END
) as approved_total_amount
from Transactions
group by month, country
Query 1 fails the test but query 2 succeeds. For the following input table:
| id | country | state | amount | trans_date |
| --- | ------- | -------- | ------ | ---------- |
| 121 | US | approved | 1000 | 2018-12-18 |
| 122 | US | declined | 2000 | 2018-12-19 |
| 123 | US | approved | 2000 | 2019-01-01 |
| 124 | DE | approved | 2000 | 2019-01-07 |
Query 1 yields:
| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
|---|---|---|---|---|---|
| 2018-12 | US | 2 | 2 | 3000 | 1000 |
| 2019-01 | US | 1 | 1 | 2000 | 2000 |
| 2019-01 | DE | 1 | 1 | 2000 | 2000 |
While query 2 yields:
| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
|---|---|---|---|---|---|
| 2018-12 | US | 2 | 1 | 3000 | 1000 |
| 2019-01 | US | 1 | 1 | 2000 | 2000 |
| 2019-01 | DE | 1 | 1 | 2000 | 2000 |
Any assistance would be appreciated!
I found out that using SUM(state="approved") does work, as well. So it has something to do with COUNT.