如何从子查询中取相应的值

时间:2013-08-06 12:52:27

标签: sql-server

我有一个这样的存储过程:

ALTER PROCEDURE [dbo].[ParkingDeatailsReportnew] 
 @startdate NVARCHAR(100),
  @enddate NVARCHAR(100)AS BEGINDECLARE  @cols AS NVARCHAR(MAX) , @query AS NVARCHAR(MAX)
 SELECT @cols = STUFF((  SELECT DISTINCT ',' + QUOTENAME(Vtype)
  FROM dbo.VType_tbl FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
 SET @query =
    'SELECT  LocName,Date, ' + @cols + '
     from  ( 
            select  l.LocName,v.Vtype, convert(date, dtime) as Date 
            from Transaction_tbl t 
            join VType_tbl v on t.vtid = v.vtid 
where dtime between ''' + @startdate + ''' and ''' + @enddate + ''' 
                and locid IN (SELECT l.Locid FROM dbo.Location_tbl l)
    ) d pivot ( count(Vtype) for Vtype in (' + @cols + ')  ) p '  EXEC sys.sp_executesql @query
END 

我这样出去了:

Date       Emaar Staff Lost Ticket Normal      VIP         VVIP
---------- ----------- ----------- ----------- ----------- -----------
2013-05-08 1           0           12          6           3
2013-05-09 0           0           1           0           0

我还有一个表名称位置表。我想在我的输出中显示特定的位置名称(locname)

预期产出

Location    Date       Emaar Staff Lost Ticket Normal      VIP               VVIP
 -------   --   -   ---------- ----------- ----------- ----------- ----------- -----------
Fasion    2013-05-08    1             0              12            6             3
blooimg  2013-05-09     0             0               1             0            0

1 个答案:

答案 0 :(得分:0)

如果您想查看输出的位置,则需要将其包含在select

'SELECT Location, Date, ' + @cols + '
 from  ( 
        select Location, v.Vtype, convert(date, dtime) as Date 
 ....