Sql server 2000 pivot查询

时间:2010-08-24 04:52:35

标签: sql-server sql-server-2000

如果以前已经回答,请原谅我。

我正在寻找有关如何构建数据透视或交叉表查询的一些建议。

我有一张看起来像这样的表

Vessel    Date    Inspector
 A      02/05/10    Morris
 B      05/20/10   Clouseau
 A      07/25/10    Gadget

我需要结果看起来像这样

Vessel  Jan   Feb      Mar     April   May   June   July   Aug   Sept   Oct    Nov  Dec
  A           Morris                                Gadget
  B                                  Clouseau

希望这是有道理的。我希望有人可以给我一些建议或帮助我开始这个。

由于

2 个答案:

答案 0 :(得分:2)

Select Vessel
    , Min ( Case When Month([Date]) = 1 Then Inspector End ) As Jan
    , Min ( Case When Month([Date]) = 2 Then Inspector End ) As Feb
    , Min ( Case When Month([Date]) = 3 Then Inspector End ) As Mar
    ...
    , Min ( Case When Month([Date]) = 12 Then Inspector End ) As Dec
From Table
Group By Vessel

您必须静态声明列。应该指出的是,这只能工作一年。如果您正在寻找的是动态列(月)生成,那么尝试在T-SQL中执行它不是正确的方法,因为您只能使用一些非常简单的动态SQL。相反,您应该使用报表生成器或中间层组件来构建结果集。

答案 1 :(得分:0)

我认为你不需要PIVOT - 只需创建12个子查询,每个月一个:

SELECT
    Vessel,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=1) as Jan,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=2) as Feb,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=3) as Mar,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=4) as Apr,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=5) as May,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=6) as Jun,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=7) as Jul,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=8) as Aug,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=9) as Sep,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=10) as Oct,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=11) as Nov,
    (SELECT TOP 1 Inspector FROM Stuff WHERE Vessel=Tbl.Vessel AND MONTH(Date)=12) as Dec
FROM (
    SELECT DISTINCT(Vessel) FROM Stuff
) Tbl

您可以通过在12个子查询的每一个末尾添加AND YEAR(Date)=2010(例如)来使这个工作适用于任何特定年份。