简体   繁体   中英

SQL Reorganize table for SSRS display

I am using MS SQL Server 2008 R2 and have a set of data as such:

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

I want to display the data for an SSRS report like with Location used in the header.

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

But with the following Code:

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

I get the following results. It seems like it would be easy to display the data correctly but I don't get the result I need to display on the report.

         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

Just add an aggregate function :

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

If you want the null values to appear at the bottom of the list, then you can use:

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

See SQL Fiddle with Demo

You can also use the PIVOT function to transform the data:

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

See SQL Fiddle with Demo

The result is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM