在少数条件下获得独特的结果

时间:2018-11-17 07:23:17

标签: 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?真的很感谢您的建议。

1 个答案:

答案 0 :(得分:1)

您可以使用“条件汇总”来“透视”您的数据。基本上,这意味着将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