在CONCAT字符串中排序结果

时间:2016-05-11 04:04:36

标签: mysql mysql-workbench

我有一张新车和二手车的表:

id  country     status  car
1   Australia   new     Honda
2   Australia   used    Alfa Romeo
3   Australia   used    Jaguar
4   Australia   used    BMW
5   Belgium     new     BMW
6   Belgium     new     Citroen
7   Belgium     used    Honda

我想计算每个国家/地区的每辆车和新车的数量,然后显示如下结果:

country     new                    used 
Australia   1 new: Honda           3 used including Alfa Romeo  
Belgium     2 new including BMW    1 used: Honda    

换句话说,如果每个国家/地区有多个“新”或“已使用”,则将它们连接到带有第一个汽车名称的字符串(按ID,优先级)。

这是我的代码:

SELECT t1.country, 
CASE 
    WHEN LENGTH(group_concat(t1.status)) - LENGTH(REPLACE(group_concat(t1.status), "new", "")) = 1 THEN CONCAT("1 new: ", t1.car)
    WHEN LENGTH(group_concat(t1.status)) - LENGTH(REPLACE(group_concat(t1.status), "new", "")) > 1 THEN CONCAT(LENGTH(group_concat(t1.status)) - LENGTH(REPLACE(group_concat(t1.status), "new", "")), " new including ", t1.car)
    ELSE ''
END as new, 
CASE 
    WHEN LENGTH(group_concat(t1.status)) - LENGTH(REPLACE(group_concat(t1.status), "used", "")) = 1 THEN CONCAT("1 used: ", t1.car)
    WHEN LENGTH(group_concat(t1.status)) - LENGTH(REPLACE(group_concat(t1.status), "used", "")) > 1 THEN CONCAT(LENGTH(group_concat(t1.status)) - LENGTH(REPLACE(group_concat(t1.status), "used", "")), " used including ", t1.car)
    ELSE ''
END as noms
from table1 t1
group by t1.country

然而,这些是我的结果:

country     new                        used 
Australia   1 new: Honda               3 used including Honda
Belgium     2 new including BMW        1 used: BMW  

在这些结果中,如果每个国家/地区有多个“新”或“已使用”,则无论状态如何,它都只是向我显示第一辆汽车。

如果有多个结果,如何让它向我展示第一辆车的状态

1 个答案:

答案 0 :(得分:1)

您可以查看此查询here

SELECT country,
  CASE
    WHEN COUNT(IF(status = 'new', id, NULL)) = 1 THEN CONCAT('1 new: ', GROUP_CONCAT(IF(status = 'new', car, NULL)))
    WHEN COUNT(IF(status = 'new', id, NULL)) > 0 THEN CONCAT(COUNT(IF(status = 'new', id, NULL)), ' new including ', SUBSTRING_INDEX(GROUP_CONCAT(IF(status = 'new', car, NULL) ORDER BY id SEPARATOR ';'), ';', 1))
    ELSE 'no new cars'
  END AS new_cars,
  CASE
    WHEN COUNT(IF(status = 'used', id, NULL)) = 1 THEN CONCAT('1 used: ', GROUP_CONCAT(IF(status = 'used', car, NULL)))
    WHEN COUNT(IF(status = 'used', id, NULL)) > 0 THEN CONCAT(COUNT(IF(status = 'used', id, NULL)), ' used including ', SUBSTRING_INDEX(GROUP_CONCAT(IF(status = 'used', car, NULL) ORDER BY id SEPARATOR ';'), ';', 1))
    ELSE 'no used cars'
  END AS used_cars
FROM cars
GROUP BY country

您可以在GROUP_CONCAT中使用ORDER BYSEPARATOR。需要第一辆车吗?使用带有SUBSTRING_INDEXORDER BY id和适当的分隔符来提取第一辆车。