php - 在mysql中获得更多条件的不同结果
问题描述
海我有一些样本数据
bookId | bookPnr | bookDate | bookFullName | bookMobile | bookEmail | bookSource
9876543210 | BPT1100000000 | 2018-11-18 | User 1 | 9876543210 | test@gmail.com | Redbus
9876543211 | BPT1100000001 | 2017-11-18 | User 2 | 9876543211 | testOne@gmail.com | Redbus
9876543212 | BPT1100000002 | 2017-11-18 | User 3 | 9876543214 | testtwo@gmail.com | TicketGoose
我需要一个类似的结果
Mobile | 2018 | 2017 | 2016 | Redbus | TicketGoose | total
9876543210 | 2 | 3 | 6 | 2 | 2 | 11
9876543211 | 1 | 1 | 1 | 2 | 1 | 3
所以我需要基于年份和来源的不同手机号码,我确实查询过类似的东西,
SELECT count(bookId), bookMobile, bookDate, bookSource FROM `booking_info`
GROUP by bookMobile, MONTH(bookDate), bookSource ORDER BY bookMobile DESC
是否可以通过单个查询来完成,或者我们必须使用 PHP 任何建议将不胜感激。
解决方案
您可以使用“条件聚合”来“透视”您的数据。基本上,这意味着在聚合函数中放置一个 case 表达式。这里我使用了 COUNT():
SELECT
bookMobile
, count(case when year(bookDate) = 2016 then 1 end) as `2016`
, count(case when year(bookDate) = 2017 then 1 end) as `2017`
, count(case when year(bookDate) = 2018 then 1 end) as `2018`
, count(case when bookSource = 'Redbus' then 1 end) as Redbus
, count(case when bookSource = 'TicketGoose' then 1 end) as TicketGoose
FROM booking_info
GROUP BY
bookMobile
ORDER BY
bookMobile DESC
推荐阅读
- html - 如何选择除特定 div 内的元素之外的所有元素
- ios - 我们可以为 2 个不同的国家/地区发布具有 1 或 2 个不同功能的相同应用程序吗?
- python - 无法通过使用 openpyxl 的列标题读取内容
- javascript - 在打字稿中获取输入值
- java - 如果插件 jar 中不同的 jar 具有相同的类名,则访问类
- algorithm - 如何证明完整二叉堆(min-heap)中第 k 个最小元素的预期深度为 O(logk)?
- server - 在 WSO2 身份服务器 5.8.0 中声明方言错误
- javascript - 如何使用 es6 过滤对象值
- git - git 子树与 Gerrit 兼容吗?
- z3 - 为什么 Z3 对于这些喇叭子句返回未知