编写查询的非Pivot版本

时间:2014-02-02 23:30:59

标签: sql-server-2005 pivot pivot-table

这是我的表结构和一些数据:

CREATE TABLE Travel 
(
  ID int primary key, 
  Name nvarchar(25),
  City nvarchar(25),
  Month varchar(3)
)

INSERT INTO Travel
(ID, Name, City, Month)
VALUES
(1, 'Name1', 'Paris','Jan'),
(2, 'Name1', 'Rome','Feb'),
(3, 'Name2', 'Italy','Jan'),
(4, 'Name2', 'Rome','Feb'), 
(5, 'Name3', 'Los Angeles','Jan'),
(6, 'Name3', 'New York','Feb');

有人可以帮我写出非Pivot版本,只有在有数据时才会返回'月'列(假设数据库在SQL Server 2005之前)。

这是一个示例查询,但它返回NULL数据列(Apr,May)

SELECT Name,
  max(CASE WHEN MONTH  = 'Jan' THEN City END) Jan,
  max(CASE WHEN MONTH = 'Feb' THEN City END) Feb,
  max(CASE WHEN MONTH = 'Mar' THEN City END) Mar,
  max(CASE WHEN MONTH = 'Apr' THEN City END) Apr,
  max(CASE WHEN MONTH = 'May' THEN City END) May
FROM Travel
GROUP BY Name

NAME    JAN    FEB       MAR     APR      MAY
Name1  Paris       Rome     (null)  (null)  (null)
Name2  Italy       Rome     (null)  (null)  (null)
Name3  Los Angeles New York (null)  (null)  (null)

此外,查询的PIVOT版本是什么,因为没有函数来聚合列?

1 个答案:

答案 0 :(得分:0)

您可以轻松地执行以下操作:

DECLARE
    @v_sql varchar(8000)
BEGIN
Set @v_sql = 'SELECT name '
If exists (select month FROM travel WHERE month='Jan')
BEGIN
  Set @v_sql = @v_sql + ',   max(CASE WHEN MONTH  = ''Jan'' THEN City END) Jan'
End

If exists (select month FROM travel WHERE month='Feb')
BEGIN
  Set @v_sql = @v_sql + ',   max(CASE WHEN MONTH  = ''Feb'' THEN City END) Feb'
End

If exists (select month FROM travel WHERE month='Mar')
BEGIN
  Set @v_sql = @v_sql + ',   max(CASE WHEN MONTH  = ''Mar'' THEN City END) Mar'
End

If exists (select month FROM travel WHERE month='Apr')
BEGIN
  Set @v_sql = @v_sql + ',   max(CASE WHEN MONTH  = ''Apr'' THEN City END) Apr'
End

If exists (select month FROM travel WHERE month='May')
BEGIN
  Set @v_sql = @v_sql + ',   max(CASE WHEN MONTH  = ''May'' THEN City END) May'
End

Set @v_sql = @v_sql + ' FROM Travel GROUP BY name'

EXECUTE(@v_sql)

END

<强>输出:

NAME     JAN           FEB
-------- ------------- -----------
Name1    Paris         Rome
Name2    Italy         Rome
Name3    Los Angeles   New York

不要忘记查看 Fiddle demo