简体   繁体   中英

SQL: for loops to create new fields based on the current values

This might be a strange question because I have never tried this and it just came to my mind. I have a table that contains a column called "countries" along with the user_ids and date. I would like to count that for each countries, how many users were active on each specific days. The easiest thing that came to my mind was to create new fields such as country_usa that shows the number of users in the usa. For example:

date ___ country_usa ___ country_england ____ country_mexico
2020 ___ 344.       ____  566            ____ 889876
2019 ___ 678        _____ 7899.         ____ 8765

I know I can create something like the table above using the case method. for example

select case when country = 'usa' then count(distinct player_id) end as country_usa

However, it seems like a lot of work especially that there are so many countries in my table. What is the faster way to do this? Is it possible to do it with a loop?

Instead you could create a view that is just the summarization of values.

Select Country, date, Count(player_id) from Table
Group By Country, date

Edit: You can also use the PIVOT function

SELECT date, [usa] AS country_usa , [england] AS country_england , [mexico] AS country_mexico 
FROM   
(SELECT Select Country, date, player_id FROM table) p  
PIVOT  
(  
COUNT (player_id )  
FOR Country IN  
( [usa], [england], [mexico])  
) AS pvt  
ORDER BY pvt.date;  

you may need to clean it up for syntax but I think this is what you're looking for

您希望case作为count()函数的参数:

select count(distinct case when country = 'usa' then player_id end) as country_usa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM