MYSQL COUNT&每个CASE都可以

时间:2015-10-17 22:18:00

标签: mysql count sum

我有像这样的mysql查询....

    "SELECT
SUM(CASE WHEN ticket_source='bpt' THEN tix_tickets.ticket_price END) AS bpt_money,
COUNT(CASE WHEN ticket_source='bpt' THEN 1 END) AS bpt_num,
SUM(CASE WHEN ticket_source='door' THEN tix_tickets.ticket_price END) AS door_money,
COUNT(CASE WHEN ticket_source='door' THEN 1 END) AS door_num,
SUM(CASE WHEN ticket_source='goldstar' THEN tix_tickets.ticket_price END) AS goldstar_money,
COUNT(CASE WHEN ticket_source='goldstar' THEN 1 END) AS goldstar_num,
COUNT(CASE WHEN ticket_price='0' THEN 1 END) AS free_tix,
COUNT(CASE WHEN ticket_price='10' THEN 1 END) AS ten_buck_tix,
COUNT(CASE WHEN ticket_price='20' THEN 1 END) AS twenty_buck_tix,
COUNT(CASE WHEN ticket_price='25' THEN 1 END) AS twentyfive_buck_tix
FROM tix_people,tix_tickets WHERE tix_people.ID=tix_tickets.holder_id GROUP BY ticket_date ORDER BY ticket_date"

并且效果很好,但我想使用表中的每个ticket_price而不单独调用它们。我想得到每个ticket_source而不单独打电话给他们。我想我可以缩短我的代码并使其更好,因为我扩大了来源和价格的数量。

1 个答案:

答案 0 :(得分:0)

你必须写出你想要选择的列。如果你想尝试构建一个查询,你可以这样做。这是你的选择的一个小重构。我清理了一些case语句只是使用布尔值

SELECT
    SUM(CASE WHEN ticket_source='bpt' THEN tix_tickets.ticket_price END) AS bpt_money,
    SUM(ticket_source='bpt') AS bpt_num,
    SUM(CASE WHEN ticket_source='door' THEN tix_tickets.ticket_price END) AS door_money,
    SUM(ticket_source='door') AS door_num,
    SUM(CASE WHEN ticket_source='goldstar' THEN tix_tickets.ticket_price END) AS goldstar_money,
    SUM(ticket_source='goldstar') AS goldstar_num,
    SUM(ticket_price='0') AS free_tix,
    SUM(ticket_price='10') AS ten_buck_tix,
    SUM(ticket_price='20') AS twenty_buck_tix,
    SUM(ticket_price='25') AS twentyfive_buck_tix
FROM tix_people
JOIN tix_tickets on tix_people.ID=tix_tickets.holder_id 
GROUP BY ticket_date 
ORDER BY ticket_date