对TransactSql进行分组

时间:2015-02-16 16:20:51

标签: sql-server sql-server-2008 tsql

我是Transact SQL的新手,所以请放轻松^^

我有下表名为

FuntionSet:

storeId   EmployeeId   ContractNum
   1        325003         3326
   2        33625          3369
   1        05             258
   2        56             6235
  ...

如何进行分组以获得每个商店的员工,如下所示

StoreID  Employee1  Employee2 ...
   1       325003      05
   2       33625       56
  ...

知道员工人数是动态的,我怎样才能实现这一目标?

欢迎任何帮助^^

2 个答案:

答案 0 :(得分:1)

select StoreId, [1] as Employee1, [2] as Employee2, ..., [10] as Employee10
from
    (
    select StoreId, EmployeeId,
    row_number(*) (partition by StoreId order by EmployeeId) as rownum
    from T
    ) as SRC
    pivot
    (min(EmployeeId)
        for rownum in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])
    ) as CT

每个商店只处理十名员工。将您的表名替换为T

答案 1 :(得分:1)

看起来你只想转动。

select StoreID , EmployeeID as [1]
      from
(
  select StoreID, EmployeeID
  from tableName
)     x
pivot
(
   max(EmployeeID)
   for StoreID in(EmployeeID)p

您必须使用select语句来准确抓取您想要的内容

这也是一种动态SQL方法。

DECLARE @cols AS NVARCHAR(MAX),
        @query AS NVARCHAR(MAX);

 select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.StoreID) 
        FROM temp c
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

 set @query = 'SELECT EmployeeID, ' + @cols + ' from 
        (
            select StoreID, EmployeeID
            from temp
       ) x
        pivot 
        (
             max(EmployeeID)
            for StoreIDin (' + @cols + ')
        ) p '


execute(@query)