我在Access 2007中有一个交叉表查询,我希望转换到SQL Server 2008.我不熟悉SQL中的交叉表方法,你能提供一些见解吗?
以下是我的Ms.Access代码。
TRANSFORM IIf(Count([Admit_ID]) Is Null,0,Count([Admit_ID])) AS Expr1
SELECT [Admits].[PatientNumber] & '-' & [Admits].[PlanCode] AS Code]
FROM Admits
WHERE (((Admits.Admitdate)>="200701") AND ((Admits.Rate)="a"))
GROUP BY [Admits.[ PatientNumber] & '-' & [Admits].[ PlanCode]
ORDER BY [Admits].[ PatientNumber] & '-' & [Admits].[ PlanCode]
PIVOT Admits. Admitdate;
结果应该是“代码”作为行,“Admit_date”作为列,“Admit_ID”作为值
非常感谢您的帮助
答案 0 :(得分:2)
为了将数据行转换为SQL Server中的列,您将应用PIVOT函数。
基本语法如下:
select *
from
(
select a.admit_id,
code = a.patientnumber + '-'+ a.plancode,
admitdate
from admits a
where a.admitdate >= '200701'
and a.rate = 'a'
) d
pivot
(
count(admit_id)
for Admitdate in (place your dates here)
) piv;
如果您提前知道admitdate
的值,则上述版本将会很有效,但如果您不知道这些值,则需要使用动态SQL来生成结果。动态版本的代码类似于以下内容:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(admitdate)
from admits
where admitdate >= '200701'
group by admitdate
order by admitdate
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT code, ' + @cols + '
from
(
select a.admit_id,
code = a.patientnumber + ''-''+ a.plancode,
admitdate
from admits a
where a.admitdate >= ''200701''
and a.rate = ''a''
) x
pivot
(
count(admit_id)
for admitdate in (' + @cols + ')
) p '
execute(@query)