sql查询(在列中显示唯一行)

时间:2013-01-02 21:45:37

标签: sql sql-server-2008 pivot

我的Sql server中有以下类型的数据: -

Field         Value   Month

Administrative  5   November
Counteracting   7   November
District1       9   November
District2       6   November
Administrative  1   December
Counteracting   2   December
District1       3   December
District2       4   December
Administrative  9   January
Counteracting   8   January
District1       5   January
District2       6   January

现在问题是我无法弄清楚如何以下列格式显示这些数据: -

Field         November   December   January

Administrative  5          1          9
Counteracting   7          2          8  
District1       9          3          5
District2       6          4          6

3 个答案:

答案 0 :(得分:4)

您要做的是PIVOT数据。有几种方法可以执行此操作。如果您提前知道这些值,那么您可以对值进行硬编码。

您可以使用带有CASE语句的聚合函数:

select field,
  sum(case when month ='November' then value end) November,
  sum(case when month ='December' then value end) December,
  sum(case when month ='January' then value end) January,
  etc
from yourtable
group by field

请参阅SQL Fiddle with Demo

在SQL Server 2005+中,您可以使用PIVOT函数:

select field, November, December, January
from
(
  select field,
    value, month
  from yourtable
) src
pivot
(
  sum(value)
  for month in (November, December, January, etc)
) piv

请参阅SQL Fiddle with Demo

如果你有一个未知数量的值要转换成列,那么你可以使用动态sql来转移数据。

答案 1 :(得分:0)

这是一个典型的转轴问题。查看SQL Server PIVOT语句:http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

它将解决您的问题。

答案 2 :(得分:0)