Mysql查询以便更好地排序结果
我正在使用的 mysql 表有一个结构:
id | type | date
--------------------------------
101 | 1 | 2011-02-08
102 | 2 | 2011-02-08
103 | 2 | 2011-02-08
104 | 2 | 2011-02-07
105 | 1 | 2011-02-07
105 | 1 | 2011-02-07
我想要做的是创建一个查询,它将给出以下结果:
total type 1 | total type 2 | date
------------------------------------------------
1 | 2 | 2011-02-08
2 | 1 | 2011-02-07
我尝试使用以下查询,但没有得到所需的结果
SELECT count(DISTINCT id) as total, date, type FROM my_table WHERE type !='0' GROUP BY date, type ORDER BY date DESC
我该怎么做? 感谢所有建议
The mysql table that I'm using has a structure:
id | type | date
--------------------------------
101 | 1 | 2011-02-08
102 | 2 | 2011-02-08
103 | 2 | 2011-02-08
104 | 2 | 2011-02-07
105 | 1 | 2011-02-07
105 | 1 | 2011-02-07
What I want to do is create a query that will give the following result:
total type 1 | total type 2 | date
------------------------------------------------
1 | 2 | 2011-02-08
2 | 1 | 2011-02-07
I tried with following query but not getting the desired result
SELECT count(DISTINCT id) as total, date, type FROM my_table WHERE type !='0' GROUP BY date, type ORDER BY date DESC
How can I do that?
Thanks for all suggestions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用:
我假设
type
列是数字,而不是像单引号建议的那样基于字符串。如果情况并非如此,请更改以适应。Use:
I'm assuming the
type
column is numeric, not string based like the single quotes suggest. Change to suit if that's not the case.试试这个:
Try this:
你要求的是枢轴功能,我猜 mysql 并不擅长。
如果它适合您,我建议将输出更改为:
并在应用程序逻辑处重新排列。它还可能使您的 SQL 更加独立于数据库。
What you're asking for is pivot functionality, which I guess mysql isn't great at.
If it works for you, I'd suggest altering the output to:
and rearrange at application logic. It would probably also make your SQL more db-independent.