使用标识列根据代理项中的重复次数创建具有动态行数的select?

时间:2014-09-24 21:33:41

标签: sql sql-server-2012

提前感谢,

我正在尝试创建一个视图,该视图部分地从一个非常基本的表中选择注释:

    Surrogate |  line_num  |     Comment
    1         |     1      |   QTY - 10
    1         |     2      |   Serial 12345 
    1         |     3      |   Serial 53234
    2         |     4      |   QTY - 5
    3         |     5      |   QTY - 6
    4         |     6      |   QTY - 7
    4         |     7      |   Serial 14455

代理在别处定义,line_num是标识列。以上是一个代表性的样本,但一些代理人最多有十条评论。我需要select(因为要进入SQL View)语句才能返回:

    Surrogate    |    Comment 1    |    Comment 2    |    Comment 3
    1            |    QTY - 10     |    Serial 12345 |  Serial 53234
    2            |    QTY - 5      |                 |
    3            |    QTY - 6      |                 |
    4            |    QTY - 7      |    Serial 14455 |

我查看了pivot命令,但它似乎并不是我想要完成的。

在此先感谢,我已经找了一段时间,但似乎找不到任何类似的东西......

1 个答案:

答案 0 :(得分:1)

您可以使用pivot或条件聚合。但是,您需要分配行号。这是条件聚合方法:

select surrogate,
       max(case when seqnum = 1 then comment end) as Comment1,
       max(case when seqnum = 2 then comment end) as Comment2,
       max(case when seqnum = 3 then comment end) as Comment3
from (select t.*, row_number() over (partition by surrogate order by line_num) as seqnum
      from basictable t
     ) t
group by surrogate;

您可以使用pivot的类似子查询。