根据SQL中的另一个列值从列获取值

时间:2014-05-06 09:55:31

标签: sql sql-server tsql

我有一张这样的表

id               code                   text

100               1           short description 100
100               2             long descr 100
101               1           short description 101

现在,我想根据text字段中的值从code字段中提取数据。如果代码是1的简短描述,并且代码是2的长描述。 我的愿望输出是这样的

id     shortdescription                    longdescription

100    short description 100               long descr 100
101    short description 101               null      

3 个答案:

答案 0 :(得分:4)

试试这个:

SELECT id,
          MAX(CASE WHEN code=1 THEN text END) as shortdescription,
          MAX(CASE WHEN code=2 THEN text END) as longdescription
   FROM TableName
GROUP BY id

结果为SQL Fiddle

此查询与以下内容相同:

SELECT id,MAX(shortdescription) as shortdescription,MAX(longdescription) as longdescription
FROM
(
   SELECT id,
          CASE WHEN code=1 THEN text END as shortdescription,
          CASE WHEN code=2 THEN text END as longdescription
   FROM TableName
) T
GROUP BY id

NB:要了解此查询的工作原理,请先执行内部查询。

结果:

ID    SHORTDESCRIPTION        LONGDESCRIPTION
100   short description 100   long descr 100
101   short description 101   (null)

请参阅SQL Fiddle中的结果。

答案 1 :(得分:3)

我认为最简单的方法是将其视为条件聚合。 。 。将case语句作为参数放入max()函数:

select id,
       max(case when code = 1 then text end) as ShortDescription,
       max(case when code = 2 then text end) as LongDescription
from table t
group by id;

答案 2 :(得分:1)

使用请求的where条件(code = 1 | 2)创建两个子查询,然后将它们连接在一起(如果其中任何一个可能丢失,则为完全外连接)。

SELECT
    COALESCE(SHORTDESC.id, LONGDESC.id) AS id
    , SHORTDESC.[text] AS shortdesc
    , LONGDESC.[text] AS longdesc
FROM (
        SELECT
            id, [text]
        FROM
            yourTable
        WHERE
            code = 1
    ) SHORTDESC
    FULL OUTER JOIN (
        SELECT
            id, [text]
        FROM
            yourTable
        WHERE
            code = 2
    ) LONGDESC
        ON SHORTDESC.id = LONGDESC.id