嗨我有一个列
的表格id desc rate rates_id
1 NYC 0.1 0001
2 NYC 0.25 0003
3 KYC 0.12 0001
4 KYC 0.15 0003
我需要以这种方式显示行
desc rate where rates_id = 0001 rate where rates_id=0003
NYC 0.1 0.25
KYC 0.12 0.15
我讨论了这个问题但没有工作
SELECT desc,
rate,
(SELECT rate
FROM tablea p
WHERE rates_id LIKE '0003'
AND p.desc = t.desc) AS rate2
FROM tablea t
WHERE rates_id LIKE '0001';
任何暗示???
答案 0 :(得分:5)
尝试:
SELECT `desc`,
MAX(CASE WHEN rates_id = '0001' THEN rate ELSE NULL END) AS `rate where rates_id = 0001`,
MAX(CASE WHEN rates_id = '0003' THEN rate ELSE NULL END) AS `rate where rates_id = 0003`
FROM table a
GROUP BY `desc`
如果您只想显示至少有一个值的行,可以在查询中附加以下内容:
HAVING MAX(CASE WHEN rates_id = '0001' THEN rate ELSE NULL END) IS NOT NULL
OR MAX(CASE WHEN rates_id = '0003' THEN rate ELSE NULL END) IS NOT NULL
或直接过滤相关的rates_id:
SELECT `desc`,
MAX(CASE WHEN rates_id = '0001' THEN rate ELSE NULL END) AS `rate where rates_id = 0001`,
MAX(CASE WHEN rates_id = '0003' THEN rate ELSE NULL END) AS `rate where rates_id = 0003`
FROM table a
WHERE rates_id IN ('0001', '0003')
GROUP BY `desc`
答案 1 :(得分:1)
您的问题是您的主查询会过滤掉子查询的结果。
您可以选择两种费率作为子选择。
SELECT distinct `desc`,
(SELECT rate
FROM tablea p
WHERE rates_id LIKE '0001'
AND p.`desc` = t.`desc`) AS rate1,
(SELECT rate
FROM tablea p
WHERE rates_id LIKE '0003'
AND p.`desc` = t.`desc`) AS rate2
FROM tablea t;
继承人sqlfiddle
或者您使用joins
来选择费率。
SELECT DISTINCT t.`desc`, rate1.rate, rate2.rate
FROM tablea t
LEFT JOIN tablea rate1 ON t.`desc` = rate1.`desc` AND rate1.rates_id = '0001'
LEFT JOIN tablea rate2 ON t.`desc` = rate2.`desc` AND rate2.rates_id = '0003'
对于联接
我建议您使用joins
,但您可能希望EXPLAIN
用于两个查询,并查看环境中成本较低的内容。