I Currently have written an sql query like this:
SELECT a, b, count(id) / ????
FROM X
group by a, b
Please pay attention to the ????? in the code above.
There are two groups in group by. Namely by columns a and b.
What I intend to do is to divide the (1) count of items in the second group (b) to the (2) count of items in the first group (a).
count(id) accomplishes (1). But I don't know what to write for (2).
P.S.: However I know It is possible to replace "????" with another complex select query, but I want to learn if there is a simpler way to aggregate items of first Group by.
Update: Sample data:
id a b
______________________
1 'A' 'G'
2 'A' 'H'
3 'A' 'H'
4 'B' 'G'
5 'B' 'G'
6 'B' 'K'
7 'B' 'K'
results:
a b [unnamed]
________________________________
'A' 'G' 0.33333
'A' 'H' 0.66667
'B' 'G' 0.5
'B' 'K' 0.5
The third column is the percentage of columns with values as in column b relative to values in column a.
Thank you.
count(*)as I have learned is not what you want, it selects all columns and on large tables, this can be a performance hit. You may want to switch tocount(eventid)assuming thateventiddoes exist and is your primary key.CREATE VIEW) for each count and then select (means "materializing") both views. But this could be a performance hit again as theseSELECTs and views can be "expensive" on large tables with many millions of rows. Maybe a better solution is to switch to a programmatic/SQL approach. First use your programming language's "count rows" method/function, then divide both and make sure division-by-zero does not happen.