带日期的SQL Server 2008透视表
我有以下数据集:带日期的SQL Server 2008透视表,sql,sql-server-2008,Sql,Sql Server 2008,我有以下数据集: site documentation_category expiry_date ------------------------------------------- Liverpool Treatment Bed Inspection 2015-03-07 00:00:00.000 Liverpool Treatment Bed Inspection 2015-03-04 00:00:00.000 Watford Treatment Bed Ins
site documentation_category expiry_date
-------------------------------------------
Liverpool Treatment Bed Inspection 2015-03-07 00:00:00.000
Liverpool Treatment Bed Inspection 2015-03-04 00:00:00.000
Watford Treatment Bed Inspection 2015-03-04 00:00:00.000
Leeds Gas Safety Record 2015-02-27 00:00:00.000
我正在尝试创建以下透视表:
site 1 2
----------------------------------
Leeds NULL 2015-02-27 00:00:00.000
Liverpool 2015-03-07 00:00:00.000 NULL
Watford 2015-03-04 00:00:00.000 NULL
但我得到了以下信息:
site 1 2
----------------
Leeds NULL NULL
Liverpool NULL NULL
Watford NULL NULL
使用以下代码时:
SELECT
[site],
[1],
[2]
FROM
(SELECT
[site],
[documentation_category],
[expiry_date]
FROM
testing) AS p
PIVOT
(
MAX([expiry_date])
FOR [documentation_category] IN
([1], [2])
) AS pvt;
提前感谢。在不使用动态SQL方法的情况下,我认为您必须实际命名要重点关注的列值,如下所示:
SELECT
[site],
[Treatment Bed Inspection],
[Gas Safety Record]
FROM
(SELECT
[site],
[documentation_category],
[expiry_date]
FROM
testing) AS p
PIVOT
(
MAX([expiry_date])
FOR [documentation_category] IN
([Treatment Bed Inspection], [Gas Safety Record])
) AS pvt
ORDER BY [site];
这将产生以下结果:
site Treatment Bed Inspection Gas Safety Record
--------- ------------------------ -----------------------
Leeds NULL 2015-02-27 00:00:00.000
Liverpool 2015-03-07 00:00:00.000 NULL
Watford 2015-03-04 00:00:00.000 NULL
(3 row(s) affected)
如果您只想关注治疗床检查
和气体安全记录
,这可能会起作用,但如果您期望有许多不同的值,并且希望关注所有值,则应动态构建查询。在本网站上搜索dynamic
pivot
sql
。这是一个很常见的问题,以前已经回答过很多次了