我需要一个 SQL 查询,可以将一个表中的多个行项目合并为一个行项目。 我有两张 table :
Table: results || Table: conditions
--------------- || ----------------------------------
| id | value | || | id | result_id | name | value |
--------------- || ----------------------------------
| 1 | 5.2 | || | 1 | 1 | temp | 5 |
| 2 | 9.9 | || | 2 | 1 | wave | 100 |
| 3 | 12.1 | || | 3 | 2 | temp | 5 |
| 4 | 6.6 | || | 4 | 2 | wave | 200 |
| | | || | 5 | 3 | temp | 25 |
| | | || | 6 | 3 | wave | 100 |
| | | || | 7 | 4 | temp | 25 |
| | | || | 8 | 4 | wave | 200 |
--------------- || ----------------------------------
条件表具有比所示更多的不同条件,但在本例中我只关心 wave
和 temp
。
我想进行一个查询,让我选择某些结果/条件,结果如下:
-----------------------------------
| result_id | temp | wave | value |
-----------------------------------
| 1 | 5 | 100 | 5.2 |
| 4 | 25 | 200 | 6.6 |
-----------------------------------
或(根据条件 temp = 5)
-----------------------------------
| result_id | temp | wave | value |
-----------------------------------
| 1 | 5 | 100 | 5.2 |
| 2 | 5 | 200 | 9.9 |
-----------------------------------
到目前为止,我已经成功地使用以下方法过滤了一个条件:
SELECT conditions.result_id, conditions.name, conditions.value, results.value
FROM conditions
INNER JOIN results ON results.id = conditions.result_id
WHERE (results.id = 1 OR results.id = 4)
AND conditions.name LIKE "temp";
-- WHERE conditions.name LIKE "temp" AND conditions.value = 5
但我不知道如何搜索与相同 result_id
匹配的 wave
并将其放在同一行。
最佳答案
您可以尝试使用条件聚合函数。 case when
与 max
函数。
查询 1:
SELECT results.id,
MAX(case when conditions.name = 'temp' then conditions.value end)temp,
MAX(case when conditions.name = 'wave' then conditions.value end)wave,
results.value
FROM conditions
INNER JOIN results ON results.id = conditions.result_id
WHERE (results.id = 1 OR results.id = 4)
GROUP BY results.id,results.value
<强> Results :
| id | temp | wave | value |
|----|------|------|-------|
| 1 | 5 | 100 | 5.2 |
| 4 | 25 | 200 | 6.6 |
关于mysql - 将多个行项目合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497275/