Oracle将行转换为列

时间:2012-01-28 05:23:43

标签: asp.net sql oracle

我从我的查询中输入了以下数据

**Date**    **HIGH**  **LOW**       **IMAGE**      **TYPE**
1/28/2012     69         42          1.jpg           SUN
1/29/2012     70         42          2.jpg           MSUN

我想将此输出转换为

**1/28/2012**       **1/29/2012**
1.jpg                    2.jpg    
Sun                       MSUN
69                         72  
42                         42

这是我的查询

SELECT 
   W_DATE,HIGH, LOW, 
   W_TYPE, IMAGE
FROM WEATHER
ORDER BY W_DATE ASC

而且我在行中有多个日期我想只显示4个日期,它们应该在系统日期被调整时更改

1 个答案:

答案 0 :(得分:0)

关于如何在oracle中从行到列的所有可能性,您可以在这里阅读:

http://www.dba-oracle.com/t_converting_rows_columns.htm

从数据库的角度来看,我没有看到一个直接的解决方案 - 建议在应用程序端进行格式化,否则它可能看起来很蹩脚:

SELECT
   to_char(w1.w_Date,'MM/DD/YYYY'), to_char(w2.w_Date,'MM/DD/YYYY'), 
   to_char(w3.w_Date,'MM/DD/YYYY'), to_char(w4.w_Date,'MM/DD/YYYY')
FROM 
 (select * from weather where w_date = trunc(sysdate)) w1,
 (select * from weather where w_date = trunc(sysdate) + 1) w2,
 (select * from weather where w_date = trunc(sysdate) + 2) w3,
 (select * from weather where w_date = trunc(sysdate) + 3) w4
UNION ALL
SELECT
   w1.image,  w2.image, w3.image , w4.image
FROM 
 (select * from weather where w_date = trunc(sysdate)) w1,
 (select * from weather where w_date = trunc(sysdate) + 1) w2,
 (select * from weather where w_date = trunc(sysdate) + 2) w3,
 (select * from weather where w_date = trunc(sysdate) + 3) w4
UNION ALL
SELECT
   w1.w_type,  w2.w_type, w3.w_type , w4.w_type
FROM 
 (select * from weather where w_date = trunc(sysdate)) w1,
 (select * from weather where w_date = trunc(sysdate) + 1) w2,
 (select * from weather where w_date = trunc(sysdate) + 2) w3,
 (select * from weather where w_date = trunc(sysdate) + 3) w4
UNION ALL
SELECT
   to_char(w1.high),  to_char(w2.high), to_char(w3.high) , to_char(w4.high)
FROM 
 (select * from weather where w_date = trunc(sysdate)) w1,
 (select * from weather where w_date = trunc(sysdate) + 1) w2,
 (select * from weather where w_date = trunc(sysdate) + 2) w3,
 (select * from weather where w_date = trunc(sysdate) + 3) w4
UNION ALL
SELECT
   to_char(w1.low),  to_char(w2.low), to_char(w3.low) , to_char(w4.low)
FROM 
 (select * from weather where w_date = trunc(sysdate)) w1,
 (select * from weather where w_date = trunc(sysdate) + 1) w2,
 (select * from weather where w_date = trunc(sysdate) + 2) w3,
 (select * from weather where w_date = trunc(sysdate) + 3) w4;
/