Php 如何将mysql行的4/5分组

Php 如何将mysql行的4/5分组,php,mysql,group-by,Php,Mysql,Group By,我从表中查询了数据,显示1天、2天、3天、4天 我想将它们显示为1-4天、5-8天、9-15天 桌上游轮: id, length(days) 1 | 1 2 | 4 3 | 5 5 | 1 6 | 3 7 | 2 目前,我可以将其显示为: 我希望它显示为: SELECT cruises.length, COUNT(cruises.id) as count FROM cruises GROUP BY cruises.length Having count > 0 ORDER BY cru

我从表中查询了数据,显示1天、2天、3天、4天

我想将它们显示为1-4天、5-8天、9-15天

桌上游轮:

id, length(days)
1 | 1
2 | 4
3 | 5
5 | 1
6 | 3
7 | 2
目前,我可以将其显示为:

我希望它显示为:

SELECT cruises.length, COUNT(cruises.id) as count FROM cruises GROUP BY cruises.length Having count > 0 ORDER BY cruises.length 

这是我到目前为止提出的问题

SELECT CASE 
WHEN cruises.length BETWEEN 1 AND 4 THEN "Upto 4 Nights"
WHEN cruises.length BETWEEN 5 AND 7 THEN "5-7 Nights" 
WHEN cruises.length BETWEEN 8 AND 14 THEN "8-14 Nights" 
WHEN cruises.length BETWEEN 15 AND 21 THEN "15-21 Nights" 
ELSE "Longer than 21 Nights" END AS cruise_length, 
COUNT(cruises.id) FROM cruises
GROUP BY cruise_length

我最终以这个问题作为我的首选答案。有没有可能我可以先点1-4,5-7秒,8-14秒再点?

我用另一个箱子做另一个专栏,不知道这样做是否正确

SELECT CASE 
WHEN cruises.length BETWEEN 1 AND 4 THEN "Upto 4 Nights"
WHEN cruises.length BETWEEN 5 AND 7 THEN "5-7 Nights" 
WHEN cruises.length BETWEEN 8 AND 14 THEN "8-14 Nights" 
WHEN cruises.length BETWEEN 15 AND 21 THEN "15-21 Nights" 
ELSE "Longer than 21 Nights" END AS cruise_length,
CASE 
WHEN cruises.length BETWEEN 1 AND 4 THEN 1
WHEN cruises.length BETWEEN 5 AND 7 THEN 2
WHEN cruises.length BETWEEN 8 AND 14 THEN 3
WHEN cruises.length BETWEEN 15 AND 21 THEN 4
ELSE 5 END AS cruise_length_id, 
COUNT(cruises.id) FROM cruises
GROUP BY cruise_length
ORDER BY cruise_length_id

您可以动态创建包含范围的表,并将其与表联接:

select r.from_length, r.to_length, count(*) as cruises
from (
  select 1 from_length ,4 as to_length
  union all select 5, 7
  union all select 8, 14
  union all select 15, 21
  union all select 21, null
) r -- range
join cruises c
  on c.length between r.from_length and coalesce(r.to_length, 10000000)
group by r.from_length, r.to_length
order by r.from_length

在PHP中,在循环行的同时创建输出:

if ($row['from_length'] == 1) {
    $label = 'Up to ' . $row['to_length'];
} elseif ($row['to_length'] === null) {
    $label = 'Longer than ' . $row['from_length'];
} else {
    $label = $row['from_length'] . ' - ' . $row['to_length'];
}
$label .= " Nights ({$row['cruises']})";

你写代码。那是你的工作。我们只是(也许)尝试帮助修复您最终编写的任何内容。至少向我们展示您要查询的表的数据结构……如果您已经知道天数,请循环生成的行,并将数据放入一个数组中,其中键是您希望它进入的组。
选择cruises.length,COUNT(cruises.id)作为cruises GROUP BY cruises.length中的count,count>0 ORDER BY cruises.length
这是我到目前为止所做的查询,您可以使用
ORDER BY MIN(cruises.length)
MAX()
也可以使用。