I’m writing a query to summarize some data. I have a flag in the table that is basically boolean, so I need some sums and counts based on one value of it, and then the same thing for the other value, like so:
select location ,count(*) ,sum(duration) from my.table where type = 'X' and location = @location and date(some_tstamp) = @date group by location
And then the same for another value of the type column. If I join this table twice, how do I still group so I can only get aggregation for each table, i.e. count(a.*) instead of count(*)…
Would it be better to write two separate queries?
EDIT
Thanks everybody, but that’s not what I meant. I need to get a summary where type = ‘X’ and a summary where type = ‘Y’ separately…let me post a better example. What I meant was a query like this:
select a.location ,count(a.*) ,sum(a.duration) ,count(b.*) ,sum(b.duration) from my.table a, my.table b where a.type = 'X' and a.location = @location and date(a.some_tstamp) = @date and b.location = @location and date(b.some_tstamp) = @date and b.type = 'Y' group by a.location
What do I need to group by? Also, DB2 doesn’t like count(a.*), it’s a syntax error.
This should work in SQL Server. I guess db2 should have something similar.
Edit: Add a where condition to limit the records to select type = X or type = Y, if ‘type’ can have value other than X and Y.