简体   繁体   English

SQL将单列中的多个值选择为多列

[英]SQL select multiple values in single column into multiple columns

I'd like to select from a single table with a simple set of data, but somehow transpose the type column into multiple columns using a simple select statement.我想从具有一组简单数据的单个表中进行选择,但是使用简单的选择语句以某种方式将类型列转换为多个列。

An example of the data I'm working with:我正在使用的数据示例:

id ID date日期 type类型
1 1 2022/06/01 2022/06/01 1 1
2 2 2022/06/01 2022/06/01 2 2
3 3 2022/06/01 2022/06/01 3 3
4 4 2022/06/01 2022/06/01 1 1
5 5 2022/06/01 2022/06/01 2 2
6 6 2022/06/01 2022/06/01 3 3

What I am hoping to achieve, using SQL only:我希望仅使用 SQL 来实现:

date_format(%y-%m-%d) date_format(%y-%m-%d) SMS短信 Email电子邮件 Online在线的
2022/06/01 2022/06/01 2 2 2 2 2 2

Any help will be greatly appreciated.任何帮助将不胜感激。

Best regards, Joel最好的问候,乔尔

If 1 means SMS, 2 means Email, and 3 means Online, then the query can look like:如果1表示 SMS, 2表示电子邮件, 3表示在线,则查询可能如下所示:

select
  date,
  sum(case when type = 1 then 1 else 0 end) as sms,
  sum(case when type = 2 then 1 else 0 end) as email,
  sum(case when type = 3 then 1 else 0 end) as online
from t
group by date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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