简体   繁体   English

SQL Server 2008数据透视表与日期

[英]SQL Server 2008 pivot table with dates

I have the following dataset: 我有以下数据集:

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

And I am trying to create the following pivot table: 我正在尝试创建以下数据透视表:

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

But I get the following: 但是我得到以下信息:

site  1  2
----------------
Leeds  NULL  NULL
Liverpool  NULL  NULL
Watford  NULL  NULL

When using the following code: 使用以下代码时:

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;

Thanks in advance. 提前致谢。

Without using a dynamic SQL approach I think you have to actually name the column values to pivot on like this: 如果不使用动态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];

This will produce the following result: 这将产生以下结果:

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)

This could work if you only ever want to pivot on Treatment Bed Inspection and Gas Safety Record but if you expect a lot of different values and want to pivot on all you should build the query dynamically. 如果您只想依靠“ Treatment Bed Inspection和“ Gas Safety Record这可能会起作用,但是如果您希望有许多不同的值并且想利用所有这些,则应该动态构建查询。 Search this site for dynamic pivot sql . 在此站点上搜索dynamic pivot sql It's a quite common question and has been answered many times before. 这是一个很常见的问题,之前已经回答了很多次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM