我对mySQL相当新,但真的很绝望。请尽量放轻松。
我想创建一个关于酒店的报告。现在,我的查询可以告诉我,有多少晚上预订了多少不同的旅程。
举个例子:
SELECT i.numberofnights,
SUM(CASE WHEN i.nod >='1' THEN '1' ELSE '0' END) as journeyCount
FROM itinerary i
WHERE i.arrival BETWEEN '2015-01-01' AND '2015-01-31'
GROUP BY i.numberofnights
我的输出:
NoN | journeyCount
1 | 18
2 | 6
3 | 4
4 | 13
5 | 12
6 | 5
7 | 9
它显示我有18个旅程,1晚,6个2晚等等。我希望做出选择,所以将结果结合1至3晚和4至7晚。 请帮帮我!
我想要的输出:
NoN | journeyCount
1-3 | 28
4-7 | 39
提前谢谢!! :)
答案 0 :(得分:1)
您可以在GROUP BY
子句中使用整数除法:
SELECT (i.numberofnights-1) DIV 3,
SUM(CASE WHEN i.nod >=1 THEN 1 ELSE 0 END) as journeyCount
FROM itinerary i
WHERE i.arrival BETWEEN '2015-01-01' AND '2015-01-31'
GROUP BY (i.numberofnights-1) DIV 3
如果您想要只有两个细分,一个用于<=3
,另一个用于> 3
,那么您可以使用:
SELECT IF(CASE WHEN i.numberofnights <= 3 THEN 0 ELSE 1 END = 0, '1-3', '4-7') AS NoN,
SUM(CASE WHEN i.nod >=1 THEN 1 ELSE 0 END) as journeyCount
FROM itinerary i
WHERE i.arrival BETWEEN '2015-01-01' AND '2015-01-31'
GROUP BY CASE WHEN i.numberofnights <= 3 THEN 0 ELSE 1 END
修改强>
要获取诸如&#39; 1-3&#39;,&#39; 4-6&#39;等桶标记,您可以使用以下查询:
SELECT CONCAT(((i.numberofnights-1) DIV 3 + 1) * 3 - 2,
'-',
((i.numberofnights-1) DIV 3 + 1) * 3) AS NoN,
SUM(CASE WHEN i.nod >=1 THEN 1 ELSE 0 END) as journeyCount
FROM itinerary i
WHERE i.arrival BETWEEN '2015-01-01' AND '2015-01-31'
GROUP BY (i.numberofnights-1) DIV 3