选择*变换行值作为表的列名(select * transform row value as tabl

2019-10-17 16:33发布

我试图改变行值作为列名。 计算器上的搜索后,我才知道,那可以使用GROUP_CONCAT()来完成。 我尝试过,但没有结果。

我想要的是??

我有这样一个表:

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');

Answer 1:

看看您需要做类似的东西查询工作:

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



Answer 2:

试试下面的代码

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;


Answer 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

见SqlFiddle



文章来源: select * transform row value as table column name