2013-02-08 81 views
1

我試圖將行值轉換爲列名。在stackoverflow上搜索後,我知道它可以通過使用GROUP_CONCAT()來完成。我嘗試過但沒有結果。select * transform row value as table列名

我想要什麼?

我有這樣的一個表:

id | staff_id_staff  | leave_type_id_leave_type | days 
1 | 41     | Casual      | 7 
2 | 41     | Earned      | 1 
3 | 41     | Sick      | 4 

,並希望結果是這樣的:

Casual | Earned | Sick 
7   |  1  | 4 

請注意:我不知道的leave_type_id_leave_type值(這將是任何東西)

這裏是leave_remain表的代碼:

CREATE TABLE IF NOT EXISTS `leave_remain` (
    `id_leave_remain` int(11) NOT NULL AUTO_INCREMENT, 
    `staff_id_staff` int(11) NOT NULL, 
    `leave_type_id_leave_type` int(11) NOT NULL, 
    `days` float DEFAULT NULL, 
    `updated` date DEFAULT NULL, 
    PRIMARY KEY (`id_leave_remain`), 
    UNIQUE KEY `leave_type_id_leave_type_UNIQUE` (`leave_type_id_leave_type`), 
    KEY `fk_leave_remain_staff1` (`staff_id_staff`), 
    KEY `fk_leave_remain_leave_type1` (`leave_type_id_leave_type`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=108 ; 

-- 
-- Dumping data for table `leave_remain` 
-- 

INSERT INTO `leave_remain` (`id_leave_remain`, `staff_id_staff`, `leave_type_id_leave_type`, `days`, `updated`) VALUES 
(82, 41, 16, 16, '2013-02-04'), 
(89, 41, 17, 178, '2013-02-06'), 
(107, 41, 18, 0, '2013-02-04'); 
+1

如果您不知道leave_type_id_leave_type的潛在值,那麼您可能需要使用動態SQL。看到這篇文章:http://stackoverflow.com/a/12005676/1073631 – sgeddes

回答

2

看看您需要做類似的查詢一些工作:

SELECT GROUP_CONCAT(CONVERT(leave_type_id_leave_type,char(10))) 
FROM leave_remain 
GROUP BY staff_id_staff 
UNION 
SELECT GROUP_CONCAT(CONVERT(days,char(10))) 
FROM leave_remain 
GROUP BY staff_id_staff 

檢查演示上SqlFiddle

+0

我得到這個結果來執行後:'[BLOB - 2B] [BLOB - 2B] [BLOB - 1B]' – user007

+0

@ user1983017 只是上面的查詢結果(左側),你會看到+選項按下它。並標記 顯示BLOB內容 我已經做了一些更正,所以它應該工作,無論如何,現在檢查 – Minesh

-1
select leave_type_id_leave_type,days, 
count(case when leave_type_id_leave_type = 'Casual' THEN 1 END) Casual, 
count(case when leave_type_id_leave_type = 'Earned' THEN 1 END) Earned, 
count(case when leave_type_id_leave_type = 'Sick' THEN 1 END) Sick 
from leave_remain GROUP BY id_leave_remain 

SqlFiddle

+0

與您的查詢創建SqlFiddle,但它不工作:( – Minesh

+0

對不起,最初我沒有創建任何架構只寫了一個示例代碼。不,我認爲它工作 –

1

試試下面的代碼

SELECT 
max(DECODE(leave_type_id_leave_type,'Casual',days)) Casual, 
max(DECODE(leave_type_id_leave_type,'Earned',days)) Earned, 
max(DECODE(leave_type_id_leave_type,'Sick',days)) Sick 
FROM table_name;