我有以下数据集:
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;
提前致谢。
答案 0 :(得分:0)
在不使用动态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)
如果你只想在Treatment Bed Inspection
和Gas Safety Record
上进行转向,这可能会有效,但是如果你期望有很多不同的值并希望转向所有,你应该动态地构建查询。在此网站上搜索dynamic
pivot
sql
。这是一个非常普遍的问题,之前已经多次回答。