如何将每个对象的多个选择值转换为1行?

时间:2014-09-02 10:05:21

标签: sql sql-server-2008

考虑以下结果集(表b

ObjectNumber  Value          Field
-----------------------------------
1             Yes            Field1
1             Foo bar baz    Field1
1             Lorem Ipsum    Field1
2             Yes            Field1
2             Foo bar baz    Field1

我正在尝试按如下方式调整此输出:

select
      ObjectNumber
    , [Yes]
    , [Foo bar baz]
    , [Lorem Ipsum]
from
    b
pivot
(
    Field for Value in
    (
          [Yes]
        , [Foo bar baz]
        , [Lorem Ipsum]

    )
) u

期望输出如:

ObjectNumber Yes  [Foo bar baz] [Lorem Ipsum]
---------------------------------------------
1            1    1             1
2            1    1             null

但这会产生错误:incorrect syntax near '[Yes]'

我做错了什么?

1 个答案:

答案 0 :(得分:1)

试试这个

select
      ObjectNumber
    , [Yes]
    , [Foo bar baz]
    , [Lorem Ipsum]
from
    t
pivot
(
    count(Field)
    for Value  in ([Yes],[Foo bar baz],[Lorem Ipsum])

) u