我有一个这样的存储过程:
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
答案 0 :(得分:1)
你错过了','。试试这个:
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