SQL重组表以显示SSRS

时间:2013-01-16 18:57:08

标签: sql sql-server-2008 tsql pivot

我正在使用MS SQL Server 2008 R2,并且拥有一组数据:

LocaId  Location  StaffId
1       Main St   1
2       South Ave 1
3       South Ave 2
4       2nd St    1
5       2nd St    2
6       Lewis Ave 1

我想显示SSRS报告的数据,例如标题中使用的位置。

          John       Mark
Location  Main St    South Ave
Location  South Ave  22nd St
Location  22nd St    Null
Location  Lewis Ave  Null

但是使用以下代码:

SELECT 'Location',
(CASE WHEN l.StaffId = 1 THEN l.Location ELSE NULL END) AS 'John',
(CASE WHEN l.StaffId = 2 THEN l.Location ELSE NULL END) AS 'Mark'
FROM Location l

我得到以下结果。看起来很容易正确显示数据但我没有得到我需要在报告上显示的结果。

         John        Mark
-------- ----------- ---------
Location Main St     NULL
Location South Ave   NULL
Location 22nd St     NULL
Location Lewis Ave   NULL
Location NULL        Main St
Location NULL        South Ave

2 个答案:

答案 0 :(得分:2)

只需添加聚合函数:

SELECT l.location,
MAX(CASE WHEN l.StaffId = 1 THEN l.Location ELSE NULL END) AS 'John',
MAX(CASE WHEN l.StaffId = 2 THEN l.Location ELSE NULL END) AS 'Mark'
FROM Location l
GROUP BY l.location

答案 1 :(得分:1)

如果您希望null值显示在列表底部,则可以使用:

SELECT 'Location',
  MAX(CASE WHEN l.StaffId = 1 THEN l.Location ELSE NULL END) AS 'John',
  MAX(CASE WHEN l.StaffId = 2 THEN l.Location ELSE NULL END) AS 'Mark'
FROM
(
  select StaffId, location,
    row_number() over(partition by StaffId order by locaid) rn
  from Location
) l
GROUP BY rn

请参阅SQL Fiddle with Demo

您还可以使用PIVOT函数转换数据:

select 'Location',
  [1] as 'John',
  [2] as 'Mark'
from
(
  select staffid, location, 
    row_number() over(partition by StaffId order by locaid) rn
  from location
) src
pivot
(
  max(location)
  for staffid in ([1], [2])
) piv

请参阅SQL Fiddle with Demo

结果是:

| COLUMN_0 |      JOHN |      MARK |
------------------------------------
| Location |   Main St | South Ave |
| Location | South Ave |    2nd St |
| Location |    2nd St |    (null) |
| Location | Lewis Ave |    (null) |