I have table consisting of these fields:
id | date_from | date_to | price | status
----------------------------------------------------------
CK1 22-12-2012 29-12-2012 800 1
CK1 22-12-2012 29-12-2012 1200 1
CK2 24-12-2012 30-12-2012 1400 0
CK2 24-12-2012 30-12-2012 1800 1
CK2 24-12-2012 30-12-2012 2200 1
How do I create SQL select that groups results by ID, DATE_FROM, DATE_TO and picks lowest value from price where status == 1 and also to count amount of how many records where grouped?
So result would be
id | date_from | date_to | price | count
CK1 22-12-2012 29-12-2012 800 2
CK2 24-12-2012 30-12-2012 1800 2
And maybe, is there a way to find out how many of records were not grouped because of status == 0? This is not very important, I am just wondering whether there is a way how to find out number of uncounted records for group of records.
Your description doesn’t match what you want the result to be.
This will match your description, i.e. give you the lowest price where status is 1, and count the number of records in the group:
Result:
This will give you the result that you asked for, i.e. filter out the records where status is 1, get you the lowest price, and get the number of records in the groups after filtering:
Result:
To get the number of records where the status is 0, you need to use the first method, where you don’t filter out those records. If the status only can be 0 or 1, you can simply use
sum(status)to get the number of records where the status is 1, andcount(case status when 0 then 1 end)orsum(1 - status)to get the number of records where the status is 0.