Get Multi Columns Count in Single Query

心不动则不痛 提交于 2019-12-11 05:00:46

问题


I am working on a application where I need to write a query on a table, which will return multiple columns count in a single query.

After research I was able to develop a query for a single sourceId, but what will happen if i want result for multiple sourceIds.

select '3'as sourceId,
   (select count(*) from event where sourceId = 3 and plateCategoryId = 3) as TotalNewCount,
   (select count(*) from event where sourceId = 3 and plateCategoryId = 4) as TotalOldCount;

I need to get TotalNewCount and TotalOldCount for several source Ids, for example (3,4,5,6)

Can anyone help, how can I revise my query to return a result set of three columns including data of all sources in list (3,4,5,6)

Thanks


回答1:


You can do all source ids at once:

select source_id
       sum(case when plateCategoryId = 3 then 1 else 0 end) as TotalNewCount,
       sum(case when plateCategoryId = 4 then 1 else 0 end) as TotalOldCount
from event
group by source_id;

Use a where (before the group by) if you want to limit the source ids.

Note: The above works in both Vertica and MySQL, and being standard SQL should work in any database.



来源:https://stackoverflow.com/questions/46888967/get-multi-columns-count-in-single-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!