我有以下mysql表: 表:出价
id | compid | itemid | rate | year
1 | 1 | 1 | 2.0 | 2015
2 | 1 | 2 | 4.2 | 2015
3 | 1 | 3 | 2.3 | 2015
4 | 2 | 1 | 3.0 | 2015
5 | 2 | 2 | 4.0 | 2015
6 | 2 | 3 | 2.5 | 2015
7 | 3 | 1 | 2.3 | 2015
8 | 3 | 2 | 4.5 | 2015
9 | 3 | 3 | 2.8 | 2015
如果我在php中使用以下mysql查询,则效果很好:
SELECT itemid, GROUP_CONCAT(rate) FROM bid GROUP BY itemid
结果:
Array ( [itemid] => 1 [GROUP_CONCAT(rate)] => 2.0,3.0,2.3 )
Array ( [itemid] => 2 [GROUP_CONCAT(rate)] => 4.2,4.0,4.5 )
Array ( [itemid] => 3 [GROUP_CONCAT(rate)] => 2.3,2.5,2.8 )
但是,如果我使用以下查询,则无效:
SELECT itemid, GROUP_CONCAT(CASE WHEN compid=1 THEN rate ELSE 0 END as company01, CASE WHEN compid=2 THEN rate ELSE 0 END as company02, CASE WHEN compid=3 THEN rate ELSE 0 END as company03) FROM bid GROUP BY itemid
我的第二个SELECT查询中的错误是什么,以及如何实现GROUP_CONCAT?
答案 0 :(得分:1)
如果你想制作列,也许这个查询。
SELECT itemid,
MAX(CASE WHEN compid = 1 THEN rate END) as 'company01',
MAX(CASE WHEN compid = 2 THEN rate END) as 'company02',
MAX(CASE WHEN compid = 3 THEN rate END) as 'company03'
FROM bid
GROUP BY itemid