0

我有这样的查询

select 
    * 
from 
   (select vtid 
    from Transaction_tbl 
    where dtime between '01-Apr-13 00:00:00' and '18-Jun-13 23:59:59' 
      and Status >= 5) p
PIVOT
    (count(vtid) FOR vtid in ([7],[8],[9],[11],[12])) as pp

此查询的输出:

7           8           9           11          12
----------- ----------- ----------- ----------- -----------
10          3           1           0           0

我还有一张桌子VType_tbl

vtid我想vtidvtype表中加载而不是硬编码。我怎样才能做到这一点?

如果有人知道怎么做,,,请帮助我

4

1 回答 1

0

如果您希望这些值是未知的,这意味着您不想对它们进行硬编码,那么您将不得不使用动态 SQL 来执行:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(vtid) 
                    from VType_tbl
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT  ' + @cols + ' 
            from 
            (
                select vtid
                from Transaction_tbl t
                where dtime between ''01-Apr-13 00:00:00'' and ''18-Jun-13 23:59:59'' 
                  and Status >= 5
            ) d
            pivot 
            (
                count(vtid)
                for vtid in (' + @cols + ')
            ) p '

execute(@query)
于 2013-06-18T13:39:15.870 回答