我有这样的查询
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
表加载vtid
,而不是硬编码vtype
。我怎么能这样做?
如果有人知道该怎么做,,,请帮帮我
答案 0 :(得分: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)