1

我正在尝试将行值转换为列名。在 stackoverflow 上搜索后,我了解到可以使用 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');
4

3 回答 3

3

看到您需要处理类似于此查询的内容:

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上的演示

于 2013-02-08T05:52:36.503 回答
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;
于 2013-02-08T05:51:40.800 回答
-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

于 2013-02-08T05:09:40.667 回答