英文:
SQL: How to generate a result that updates columns based on the data?
问题
Suppose we have a database (I'm using Snowflake) which keeps updating books based on which country it was released from.
Date | Book Name | Country |
---|---|---|
22-03-2023 | book1 | US |
22-03-2023 | book2 | CA |
22-03-2023 | book3 | RU |
22-03-2023 | book4 | US |
22-02-2023 | book5 | US |
Is there a way we can query it such that I get a total count in a different column without having to hardcode the countries in a for loop or something?
I'm expecting the output to be something that's grouped by date and has separate columns for each country count, something like this:
Date | US_Count | CA_Count | RU_Count |
---|
Is it possible to achieve this?
英文:
Suppose we have a database (I'm using Snowflake) which keeps updating books based on which country it was released from.
Date | Booke Name | Country |
---|---|---|
22-03-2023 | book1 | US |
22-03-2023 | book2 | CA |
22-03-2023 | book3 | RU |
22-03-2023 | book4 | US |
22-02-2023 | book5 | US |
Is there a way we can query it such that I get a total count in a different column without having to hardcode the countries in a for loop or something?
I'm expecting the output to be something that's grouped by date and has separate columns for each country count, something like this:
Date | US_Count | CA_Count | RU_Count |
---|
Is it possible to achieve this?
答案1
得分: 1
如果我理解正确,您可以使用GROUP BY子句和COUNT()函数。
SELECT
Date,
COUNT(CASE WHEN Country = 'US' THEN 1 ELSE NULL END) AS US_Count,
COUNT(CASE WHEN Country = 'CA' THEN 1 ELSE NULL END) AS CA_Count,
COUNT(CASE WHEN Country = 'RU' THEN 1 ELSE NULL END) AS RU_Count
FROM
books_table
GROUP BY
Date;
https://www.datacamp.com/tutorial/count-sql-function
英文:
If I got this right, you can use the GROUP BY clause and the COUNT() function.
SELECT
Date,
COUNT(CASE WHEN Country = 'US' THEN 1 ELSE NULL END) AS US_Count,
COUNT(CASE WHEN Country = 'CA' THEN 1 ELSE NULL END) AS CA_Count,
COUNT(CASE WHEN Country = 'RU' THEN 1 ELSE NULL END) AS RU_Count
FROM
books_table
GROUP BY
Date;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论