Oracle行到列

时间:2014-01-08 09:02:26

标签: sql oracle

我有一个包含以下列和2行的表:

COL1,COL2,COL3,NAME,DATE

两行中COL1,COL2,COL3的值为A,B,C。第一行中NAME的值为“DEL”,第二行为“LAP”。第一行中DATE的值为'11 .12.13',第二行为'13 .11.13'。

现在我想要一个带有singlerow和跟随列的视图

COL1,COL2,COL3,DEL,LAP with values A,B,C,11.12.13,13.11.13.

是否可以使用枢轴或任何其他功能

感谢

3 个答案:

答案 0 :(得分:0)

with tab (COL1,COL2,COL3,N_NAME,D_DATE) as ( 
select  'A','B','C', 'DEL', '11.12.13' from dual union all
select  'A','B','C', 'LAP', '13.11.13' from dual)
select COL1, COL2, COL3, 
       min(decode(N_NAME, 'DEL', D_DATE, NULL)) DEL,
       min(DECODE(N_NAME, 'LAP', D_DATE, NULL)) LAP
from tab
group by COL1, COL2, COL3 

输出

| COL1 | COL2 | COL3 |      DEL |      LAP |
|------|------|------|----------|----------|
|    A |    B |    C | 11.12.13 | 13.11.13 |

答案 1 :(得分:0)

假设两行中的公共字段是COL1,COL2和COL3。

SELECT a.col1, 
       a.col2, 
       a.col3, 
       a.date AS DEL, 
       b.date AS LAP 
FROM   yourtable AS a 
       INNER JOIN yourtable AS b 
               ON a.col1 = b.col1 
                  AND a.col2 = b.col2 
                  AND a.col3 = b.col3 
                  AND a.name = 'DEL' 
                  AND b.name = 'LAP' 

答案 2 :(得分:0)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name (COL1,COL2,COL3,N_NAME,D_DATE) AS 
          SELECT  'A','B','C', 'DEL', '11.12.13' FROM DUAL
UNION ALL SELECT  'A','B','C', 'LAP', '13.11.13' FROM DUAL
UNION ALL SELECT  'A','B','C', 'DEL', '12.12.13' FROM DUAL
UNION ALL SELECT  'A','B','C', 'LAP', '14.11.13' FROM DUAL;

查询1

如果COL1COL2COL3N_Name的组合是唯一的,那么您可以这样做:

SELECT Col1,
       Col2,
       Col3,
       MIN( CASE N_Name WHEN 'DEL' THEN D_Date END ) AS DEL,
       MIN( CASE N_Name WHEN 'LAP' THEN D_Date END ) AS LAP
FROM   table_name
GROUP BY
       Col1,
       Col2,
       Col3

<强> Results

| COL1 | COL2 | COL3 |      DEL |      LAP |
|------|------|------|----------|----------|
|    A |    B |    C | 11.12.13 | 13.11.13 |

查询2

但是,如果您有多个行具有COL1COL2COL3N_Name的相同组合,并且您希望所有这些行都返回(按日期顺序排列) )那么你可以这样做:

WITH indexed_data AS (
  SELECT Col1,
         Col2,
         Col3,
         N_Name,
         D_Date,
         ROW_NUMBER() OVER ( PARTITION BY Col1, Col2, Col3, N_Name ORDER BY D_Date ) AS idx
  FROM   table_name  
)
SELECT Col1,
       Col2,
       Col3,
       MIN( CASE N_Name WHEN 'DEL' THEN D_Date END ) AS DEL,
       MIN( CASE N_Name WHEN 'LAP' THEN D_Date END ) AS LAP
FROM   indexed_data
GROUP BY
       Col1,
       Col2,
       Col3,
       idx
ORDER BY
       Col1,
       Col2,
       Col3,
       idx

<强> Results

| COL1 | COL2 | COL3 |      DEL |      LAP |
|------|------|------|----------|----------|
|    A |    B |    C | 11.12.13 | 13.11.13 |
|    A |    B |    C | 12.12.13 | 14.11.13 |