1

我在 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”作为值

非常感谢您的帮助

4

1 回答 1

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)
于 2013-07-07T17:22:23.827 回答