Mysql 如何从同一个表列中获取高度和重量的两个查询结果

Mysql 如何从同一个表列中获取高度和重量的两个查询结果,mysql,Mysql,我有一个表,基本上包含了身高、体重和学生日期(sid)。高度和重量包含在同一列中:百分比,枚举列包含高度和重量。 两者的条目具有完全相同的日期: -- Table structure and sample data for table `PROGWandH` -- CREATE TABLE `wandh` ( `Wid` int(24) NOT NULL, `sid` int(4) NOT NULL, `date` timestamp NOT NULL DEFAULT CURRENT

我有一个表,基本上包含了身高体重和学生日期(sid)。高度重量包含在同一列中:
百分比
,枚举列包含高度和重量。 两者的条目具有完全相同的日期:

-- Table structure and sample data for table `PROGWandH`
--
CREATE TABLE `wandh` (
  `Wid` int(24) NOT NULL,
  `sid` int(4) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `level` enum('height','weight') NOT NULL,
  `Percent` decimal(5,1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `PROGWandH` (`Wid`, `sid`, `date`, `level`, `Percent`) VALUES
(157, 55, '2020-01-13 15:00:00', 'weight', '20.2'),
(131, 55, '2019-12-12 15:00:00', 'weight', '19.8'),
(121, 55, '2019-11-14 15:00:00', 'weight', '19.3'),
(774, 55, '2020-01-13 15:00:00', 'height', '113.0'),
(749, 55, '2019-12-12 15:00:00', 'height', '112.0'),
(739, 55, '2019-11-14 15:00:00', 'height', '111.5');
--
ALTER TABLE `wandh`
  ADD PRIMARY KEY (`Wid`);

我正在尝试生成一个包含高度、宽度和日期列的列表。我使用的PHP一个接一个地生成一个集合,但我需要生成高度、重量、日期、高度、重量等列表。 到目前为止,我所尝试的方法会生成重复的结果,因此无法同步输出:

select Percent, s1.Percent1, date
from wandh
JOIN (SELECT DISTINCT Percent as 'Percent1' from wandh where level = 'weight' and sid = 55) as s1
      where sid = 55 and level = 'height';

我试过的其他变体不起作用

select level, Percent, date from wandh where level like '%eight' and sid = 55;

我缺少什么?

您可以使用条件聚合来完成:

select sid, date,
  max(case when level = 'weight' then percent end) weight,
  max(case when level = 'height' then percent end) height
from wandh
group by sid, date
请参阅。
结果:


天哪,谢谢你!非常合身。你刚刚保存了我们学生的毕业图表页面!
select sid, date,
  max(case when level = 'weight' then percent end) weight,
  max(case when level = 'height' then percent end) height
from wandh
group by sid, date
| sid | date                | weight | height |
| --- | ------------------- | ------ | ------ |
| 55  | 2019-11-14 15:00:00 | 19.3   | 111.5  |
| 55  | 2019-12-12 15:00:00 | 19.8   | 112    |
| 55  | 2020-01-13 15:00:00 | 20.2   | 113    |