也许它只是非常简单我希望基于不同的where子句有几个计数,并将结果输入两列,一列带有虚拟条目,另一列带有每个where子句的计数。我表现得更好: 我的声明在MSSQL 2008中运行良好,但输出需要格式化:
SELECT (
SELECT COUNT(*)
from [Tasks].[dbo].[Lifecycle]
where oldwsid like '%L%' and Quarter = 'Q1'
) as 'Total Laptops',
(
SELECT COUNT(*)
from [Tasks].[dbo].[Lifecycle]
where oldwsid like '%W%' and Quarter = 'Q1'
) as 'Total Desktops'
结果是:( 1行,有两列)
Total Laptops | Total Desktops 100 20
但我希望这样:(2行2列)
Total Laptops 100 Total Desktops 20像这样,我可以轻松超越它。有这种虚拟列的方法吗?
非常感谢您的帮助
答案 0 :(得分:0)
UNION可以解决您的问题
DECLARE @cols AS NVARCHAR(MAX),
@cols2 AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(pergunta)
from [dbo].[VRespostas]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @cols2 = '[NQuestionario],[Data],[Utilizador],' + @cols + ',[SubCategoria],[Observacoes]'
print @cols + ' '+ @cols2
set @query = 'SELECT ' + @cols2 + ' from
(
select *
from [dbo].[VRespostas]
) x
pivot
(
max(Resposta)
for Pergunta in (' + @cols + ')
) p '
execute(@query)