SQL:如何生成一个根据数据更新列的结果?

huangapple go评论85阅读模式
英文:

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()函数。

  1. SELECT
  2. Date,
  3. COUNT(CASE WHEN Country = 'US' THEN 1 ELSE NULL END) AS US_Count,
  4. COUNT(CASE WHEN Country = 'CA' THEN 1 ELSE NULL END) AS CA_Count,
  5. COUNT(CASE WHEN Country = 'RU' THEN 1 ELSE NULL END) AS RU_Count
  6. FROM
  7. books_table
  8. GROUP BY
  9. 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.

  1. SELECT
  2. Date,
  3. COUNT(CASE WHEN Country = 'US' THEN 1 ELSE NULL END) AS US_Count,
  4. COUNT(CASE WHEN Country = 'CA' THEN 1 ELSE NULL END) AS CA_Count,
  5. COUNT(CASE WHEN Country = 'RU' THEN 1 ELSE NULL END) AS RU_Count
  6. FROM
  7. books_table
  8. GROUP BY
  9. Date;

https://www.datacamp.com/tutorial/count-sql-function

huangapple
  • 本文由 发表于 2023年4月11日 13:42:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定