我有一个这样的存储过程:
ALTER PROCEDURE [dbo].[ParkingSummary]
@locid INTEGER,
@startdate NVARCHAR(100),
@enddate NVARCHAR(100)
AS
BEGIN
DECLARE @cols AS NVARCHAR(MAX)
,@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((
SELECT DISTINCT ',' + QUOTENAME(Vtype)
FROM VType_tbl
FOR XML PATH (''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT ' + @cols + ' from
( select Vtype from Transaction_tbl t inner join VType_tbl v on t.vtid = v.vtid
where dtime between ''' + @startdate + ''' and ''' + @enddate + ''' and locid = ' +
CAST(@locid AS VARCHAR(MAX)) + ' and Status >= 5 ) d
pivot ( count(Vtype) for Vtype in (' + @cols + ') ) p '
EXECUTE (@query)
END
我的输出是这样的:
Emaar Staff Lost Ticket Normal VIP VVIP
----------- ----------- ----------- ----------- -----------
0 0 455 0 0
0 0 2537 1831 0
我还有一个表名位置,我还想显示位置。所以我像这样重写我的查询以获取位置名称
ALTER PROCEDURE [dbo].[ParkingSummary]
@locid INTEGER,
@startdate NVARCHAR(100),
@enddate NVARCHAR(100)
AS
BEGIN
DECLARE @cols AS NVARCHAR(MAX)
,@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((
SELECT DISTINCT ',' + QUOTENAME(Vtype)
FROM VType_tbl
FOR XML PATH (''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT LocName ' + @cols + ' from
( select l.LocName, Vtype from Transaction_tbl t inner join VType_tbl v on t.vtid = v.vtid
join dbo.Location_tbl l on t.locid=l.Locid
where dtime between ''' + @startdate + ''' and ''' + @enddate + ''' and Status >= 5 ) d
pivot ( count(Vtype) for Vtype in (' + @cols + ') ) p '
EXECUTE (@query)
END
所以我的结果是这样的:
Emaar Staff Lost Ticket Normal VIP VVIP
----------- ----------- ----------- ----------- -----------
AddressHotel 0 455 0 0
Fashionavenu 0 2537 1831 0
我的位置名称替换 emaarstaff 结果。
Location1name Emaar Staff Lost Ticket Normal VIP VVIP
----------- ----------- ----------- ----------- --------------------------
AddressHotel 0 455 0 0 10
Fashionavenu 0 2537 1831 0 10