透视查询问题

时间:2011-05-05 09:06:13

标签: sql-server tsql

我在t-sql中有一个表函数,它根据作业号

返回3个条目中的拆分值 例如

JobNumber SplitValue
J1             A
J1             B
J1             C

任何人都可以帮助使用会转换结果集的pivot语句 所以我得到了

JobNumber SplitValue1, SPlitValue2, SPlitValue3

提前致谢

1 个答案:

答案 0 :(得分:1)

以下内容应该在Oracle下运行,我希望它可以帮助您获得一个想法:

WITH t AS
 (SELECT 'J1' JOBNUMBER, 'A' SPLITVALUE FROM dual
  UNION ALL
  SELECT 'J1' JOBNUMBER, 'B' SPLITVALUE FROM dual
  UNION ALL
  SELECT 'J1' JOBNUMBER, 'C' SPLITVALUE FROM dual
  UNION ALL
  SELECT 'J2' JOBNUMBER, 'Z' SPLITVALUE FROM dual
  UNION ALL
  SELECT 'J2' JOBNUMBER, 'X' SPLITVALUE FROM dual
  UNION ALL
  SELECT 'J2' JOBNUMBER, 'Y' SPLITVALUE FROM dual)
----
  select JOBNUMBER, max(SPLITVALUE1), max(SPLITVALUE2), max(SPLITVALUE3)
  from (
  select
    JOBNUMBER,
    case when row_number() over (partition by jobnumber order by SPLITVALUE) = 1 then SPLITVALUE else null end SPLITVALUE1,
    case when row_number() over (partition by jobnumber order by SPLITVALUE) = 2 then SPLITVALUE else null end SPLITVALUE2,
    case when row_number() over (partition by jobnumber order by SPLITVALUE) = 3 then SPLITVALUE else null end SPLITVALUE3
  from t )
group by JOBNUMBER order by jobnumber

输出:

JOBNUMBER SPLITVALUE1      SPLITVALUE2      SPLITVALUE3
--------- ---------------- ---------------- ----------------
J1        A                B                C
J2        X                Y                Z