2010-09-27 65 views
4

以下查詢按預期工作。將列轉置爲行

但是,如何獲得列中顯示的結果?

select curdate() AS one, 
date_sub(curdate(), interval 15 day) AS two 
, date_sub(curdate(), interval 30 day) AS three 
, date_sub(curdate(), interval 45 day) AS four 
, date_sub(curdate(), interval 60 day) AS five 
, date_sub(curdate(), interval 75 day) AS six 
, date_sub(curdate(), interval 90 day) AS seven 
; 

| one  | two  | three  | four  | five  | six  | seven  | 
+------------+------------+------------+------------+------------+------------+------------+ 
| 2010-09-27 | 2010-09-12 | 2010-08-28 | 2010-08-13 | 2010-07-29 | 2010-07-14 | 2010-06-29 | 

預期結果在一排:

one 2010-09-27 
two 2010-09-12 
three 2010-08-28 
four 2010-08-13 
five 2010-07-29 
six 2010-07-14 
seven 2010-06-29 

回答

7

您可以使用UNION ALL這個

select 'one' as label, curdate() as val 
UNION ALL 
select 'two' as label, date_sub(curdate(), interval 15 day) as val 
UNION ALL 
select 'three' as label, date_sub(curdate(), interval 30 day) as val 
UNION ALL 
select 'four' as label, date_sub(curdate(), interval 45 day) as val 
UNION ALL 
select 'five' as label, date_sub(curdate(), interval 60 day) as val 
UNION ALL 
select 'six' as label, date_sub(curdate(), interval 75 day) as val 
UNION ALL 
select 'seven' as label, date_sub(curdate(), interval 90 day) as val 
+0

我認爲,如果你的列是相同的數據類型這隻適用。我得到這個錯誤:'將varchar值'fieldx'轉換爲數據類型int時轉換失敗'。 – Misi 2013-10-02 07:19:35

+1

@Misi您需要將數字列轉換爲字符串。 – 2013-10-02 07:21:05

+0

你有SP嗎?因爲我只需要知道表名即可動態提取數據。如果我有多行,我該如何轉置? – Misi 2013-10-02 07:30:53