0

嗨,我有一个带列的表

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';  

有什么建议吗???

4

2 回答 2

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`
于 2013-07-09T08:33:15.170 回答
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'

用于连接的sqlfiddle

我建议您使用joins,但您可能希望同时使用EXPLAIN这两个查询,看看在您的环境中什么成本更低。

于 2013-07-09T08:33:13.680 回答