select * transform row value as table column name

跟風遠走 提交于 2019-12-24 14:36:06

问题


I am trying to transform row value as column name. After searching on stackoverflow I learned that it can be done by using GROUP_CONCAT(). I tried it but no result.

what I want??

i have a table like this :

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

and want result like this:

Casual    |    Earned   |   Sick
7         |       1     |   4

Please note: I dont know the value of leave_type_id_leave_type (it will be anything)

Here is the code of leave_remain table:

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:


See you need to work on something similar to this query:

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

Check demo on SqlFiddle




回答2:


Try the below code

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;



回答3:


  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

See SqlFiddle



来源:https://stackoverflow.com/questions/14765765/select-transform-row-value-as-table-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!