1

我不想创建聚合函数 ( sum, count, max)。PIVOT需要那个。

我的问题是,早在我出生之前的某个人可能将数据“读取”为两列,实际上应该是每列 1 个值的列数据,乘以“n”条记录。

他们的数据集:

(RECORDSET, NAME, VALUE)
(1, FIELD1, char1-1)
(1, FIELD2, char2-1)
(1, FIELD3, int3-1)
(1, FIELD4, char4-1)
(…)
(…)
(…)
(1, FIELD26, float26-1)
(2, FIELD1, char1-2)
(2, FIELD2, char2-2)
(2, FIELD3, int3-2)
(2, FIELD4, char4-2)
(…)
(…)
(…)
(2, FIELD26, float26-2)
(3, FIELD1, char1-3)
(3, FIELD2, char2-3)
(3, FIELD3, int3-3)
(3, FIELD4, char4-3)
(…)
(…)
(…)
(3, FIELD26, float26-3)

我需要每组 26 条记录是这样的:

FIELD1......FIELD2......FIELD3......FIELD4.............FIELD 26
char1-1.....char2-1.....int3-1......char4-1............float26-1
char1-2.....char2-2.....int3-2......char4-2............float26-2
char1-3.....char2-3.....int3-3......char4-3............float26-3

等等。

4

1 回答 1

1

我会使用支点,所以我包括了支点版本和其他一些选项。

具有枢轴和聚合的版本。SE-数据

select P.FIELD1, P.FIELD2, P.FIELD3, P.FIELD4
from YourTable T
pivot (min(T.VALUE) for T.NAME in (FIELD1, FIELD2, FIELD3, FIELD4)) P

没有枢轴但仍使用聚合的版本。SE-数据

select min(case when T.NAME = 'FIELD1' then T.VALUE end) as FIELD1,
       min(case when T.NAME = 'FIELD2' then T.VALUE end) as FIELD2,
       min(case when T.NAME = 'FIELD3' then T.VALUE end) as FIELD3,
       min(case when T.NAME = 'FIELD4' then T.VALUE end) as FIELD4
from (select RECORDSET, NAME, VALUE from YourTable) T
group by T.RECORDSET

没有枢轴,也没有聚合。SE-数据

select T.R.value('(VALUE[@Name = "FIELD1"])[1]', 'varchar(10)') as FIELD1,
       T.R.value('(VALUE[@Name = "FIELD2"])[1]', 'varchar(10)') as FIELD2,
       T.R.value('(VALUE[@Name = "FIELD3"])[1]', 'varchar(10)') as FIELD3,
       T.R.value('(VALUE[@Name = "FIELD4"])[1]', 'varchar(10)') as FIELD4
from
    (
      select (select T1.NAME as "@Name",
                     T1.VALUE as "*"
              from @T T1
              where T1.RECORDSET = T.RECORDSET
              for xml path('VALUE'), root('RECORDSET'), type)
      from YourTable T
      group by T.RECORDSET
      for xml path(''), type
    ) X(XML)
  cross apply X.XML.nodes('RECORDSET') as T(R)

另一个无枢轴无聚合版本。SE-数据

select (select T2.VALUE
        from YourTable T2
        where T.RECORDSET = T2.RECORDSET and
              T2.NAME = 'FIELD1') as FIELD1,
       (select T2.VALUE
        from YourTable T2
        where T.RECORDSET = T2.RECORDSET and
              T2.NAME = 'FIELD2') as FIELD2,
       (select T2.VALUE
        from YourTable T2
        where T.RECORDSET = T2.RECORDSET and
             T2.NAME = 'FIELD3') as FIELD3,
       (select T2.VALUE
        from YourTable T2
        where T.RECORDSET = T2.RECORDSET and
             T2.NAME = 'FIELD4') as FIELD4
from YourTable T
group by T.RECORDSET
于 2012-05-23T05:15:29.677 回答