How to get two query results from the same table column for height and weight

DJ Taiga :

I have a table that essentially contains both height, weight and date of students (sid). The height and weight are contained in the same column: 'Percent' and an enum column contains height and weight. Entries for both have the exact same date:

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

I'm trying to generate a list with columns height, width and date. The PHP I use generates one set each, one after the other, but I need to generate the list as height, weight, date, height, weight, etc. What I've tried so far generates duplicates, so the output isn't synced:

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

and

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

Other variations I've tried don't work.

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

What am I missing?

forpas :

You can do it with conditional aggregation:

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

See the demo.
Results:

| 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    |

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297574&siteId=1