作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
select pd.products_name,
GROUP_CONCAT(pag.customers_group_id SEPARATOR ',') group_id,
pa.`options_values_price` Retail,
GROUP_CONCAT(pag.options_values_price SEPARATOR ',') volume_and_designer
from products_attributes pa
left join products_description pd
on pa.products_id = pd.products_id and pd.language_id = '1'
left join products_attributes_groups pag
on pa.`products_attributes_id`= pag.`products_attributes_id`
where pa.products_id='225'
GROUP BY `pa`.`products_attributes_id`
ORDER BY `pa`.`products_attributes_id` ASC
上面的查询返回这样的输出
| products_name | group_id | Retail | volume_and_sdesign |
-------------------------------------------------------------
| GOLD | 1,2 | 15 | 30,35 |
| SILVER | 2,1 | 16 | 40,45 |
| BRONZE | 1,2 | 17 | 50,55 |
我想要实现的是在上表中再添加 2 个别名,以便根据 group_id 列将最后一列(volume_and_sdesign)分成两列(即 volume,SDesign)。 1对应volume,2对应SDesign。
例如
Gold has group_id (1,2)
so its volume_and_sdesign (30,35) will make new columns
volume = 30
SDesign = 35
Silver has group_id (2,1)
so its volume_and_sdesign (40,45) will make new columns
volume = 45
SDesign = 40
Bronze has group_id (1,2)
so its volume_and_sdesign (50,55) will make new columns
volume = 50
SDesign = 55
所以,上表看起来是这样的
| products_name | group_id | Retail | volume_and_sdesign | volume | SDesign|
-------------------------------------------------------------
| GOLD | 1,2 | 15 | 30,35 |30 | 35 |
| SILVER | 2,1 | 16 | 40,45 |45 | 40 |
| BRONZE | 1,2 | 17 | 50,55 |50 | 55 |
任何帮助将不胜感激
最佳答案
您可以使用条件聚合——即 case
在聚合函数中,例如 max()
:
select pd.products_name,
group_concat(pag.customers_group_id SEPARATOR ',') as group_id,
pa.`options_values_price` as Retail,
group_concat(pag.options_values_price SEPARATOR ',') as volume_and_designer,
max(case when group_id = 1 then pag.options_values_price end) as volume,
max(case when group_id = 2 then pag.options_values_price end) as SDesign
from products_attributes pa left join
products_description pd
on pa.products_id = pd.products_id and pd.language_id = '1' left join
products_attributes_groups pag
on pa.`products_attributes_id` = pag.`products_attributes_id`
where pa.products_id='225'
group by `pa`.`products_attributes_id`
order by `pa`.`products_attributes_id` ASC
关于MySql 将别名拆分为多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36331786/
我是一名优秀的程序员,十分优秀!