Java—sql about merging results under different conditions

Scenes:

        Query the same table with different query conditions, but want to combine the query results? Use case when to handle different query conditions.


example:

sql1:

select user_name as username, count(0) as visits from j group by user_name

sql2:

select user_name as username, count(0) as valid times from j where valid='1' group by user_name

At this point, the results of sql1 and sql2 should be merged:

Merge sql:

select user_name as username, count(0) as number of visits, sum(case when valid='1' then 1 else 0 end) as valid number of times from j group by user_name

The above is the use of case when to merge sql, and more usages are welcome to share!

Finally, I wish you all a safe year and no bugs!

Guess you like

Origin blog.csdn.net/m0_65410121/article/details/124989229