I have a table
cab | name | value |
---|---|---|
1 | PHP | 1 |
1 | PHP | 2 |
1 | PHP | 0 |
2 | LHL | 0 |
3 | GHG | 3 |
3 | GHG | 2 |
I am looking to get the distinct cab and name plus how many values =0 and how many are >0
the result table should look like this:
cab | name | value=0 | value>0 |
---|---|---|---|
1 | PHP | 1 | 2 |
2 | LHL | 1 | 0 |
3 | GHG | 0 | 2 |
third column represents how many values =0
forth column represents how may values >0
I’ve been trying all day but I cant seem to figure out the correct sql statement
3
Answers
I know that the title say "subquery using distinct", but the easier way to solve problem like this is using CTEs and the base value tecnic.
I wrote this SQL that solve the problem.
This simple code use 3 CTEs. The first (CTE1) count how many times there is value = 0. The second (CTE2) count how many time there is value > 0. The last CTE (base_value) is just a List with all the possibile combination of Cap and Name. After declering this CTE, you can simply union the result in the last statement.
I hope this will help you. Sorry for not using the subquey (you can try to convert this code if you realy need that) and sorry for my bad english too.
I got two options for you.It works fine in your test case ^^
No need for a subquery or
DISTINCT
here, that’s a use case ofconditional aggregation
.We will simply use
GROUP BY
and sum the occurences of values = 0 and values > 0.If the column
value
is not nullable, this will do:If the column is nullable, the above query can return
NULL
. If this is not intended, we can useSUM(IF...)
to enforce a result of0
in such cases:Try out here