开发者

counting with conditions in mysql

开发者 https://www.devze.com 2023-04-08 07:55 出处:网络
im a bit stuck in a quite simple query i have these 4 columns in the table id1 (unique), id2 (can repeat) , updated (boolean), updated_on

im a bit stuck in a quite simple query

i have these 4 columns in the table

id1 (unique), id2 (can repeat) , updated (boolean), updated_on

what i want now is to get a summary in the form

id2, count of updates , max (updated_on)

in short i want the result sorted by the recent updated_on while counting all rows for this id2 where update=1

and for ids that donot have any update=1, show 0, with the max updated_on

______________________
id2|_count__|___date__
1  |   0    | 11/03/05,
开发者_运维百科3  |   5    | 11/03/04,
6  |   3    | 11/03/03,
2  |   0    | 11/03/02,

i used this query :

select id2, count(updated),max(updated_on) from table
where updated=1
group by need_id_to

but this query doesnot bring results where count would be 0 (for obvious reasons because im adding a condition in the where clause)


A boolean field is 1 for true and 0 for false.
You can use this to get the count of all updated = true rows.

SELECT
  id2
  , SUM(updated) as updates
  ,MAX(updated_on) as last_update
FROM table1
GROUP BY id2
ORDER BY last_update DESC


select id2, 
       count(case 
               when updated=1 then updated 
               else null 
             end) updates_count,
       max(updated_on) last_updated
from table
group by id2
order by last_updated desc


select id2, 
       SUM(CASE WHEN updated=1 THEN 1 ELSE 0 END) AS UpdatedCount,
       max(updated_on) 
    from table
    group by id2
0

精彩评论

暂无评论...
验证码 换一张
取 消