表:数据表
+----+-------+-------+
| Id | Name | Value |
+----+-------+-------+
| 50 | Eric | 1200 |
| 50 | Barb | 1195 |
| 50 | Joe | 1180 |
| 51 | Barb | 6 |
| 51 | Eric | 3 |
| 51 | Joe | 5 |
+----+-------+-------+
我想要这个结果
+-------+---------+--------+
| Name | Value1 | Value2 |
+-------+---------+--------+
| Eric | 1200 | 3 |
| Barb | 1195 | 6 |
| joe | 1180 | 5 |
+-------+---------+--------+
我不知道如何合并。
SELECT name, value from datatable WHERE Id=50 AS Value1
JOIN datatable
WHERE Id=51 AS Value2 ON value1.Name = value2.Name ORDER BY value1.Value
不知道该怎么打value2
?
$row["??"]
答案 0 :(得分:1)
Group By
上进行Name
。Case .. When
和Max()
函数来利用条件聚合。尝试以下查询:
SELECT
t.Name,
MAX(CASE WHEN t.Id = 50 THEN t.VALUE END) AS Value1,
MAX(CASE WHEN t.Id = 51 THEN t.VALUE END) AS Value2
FROM datatable AS t
GROUP BY t.Name
答案 1 :(得分:0)
使用表别名
SELECT t1.name, t1.value AS Value1,t2.value AS Value2 from datatable t1
JOIN datatable t2 ON t1.Name = t2.Name
WHERE t1.Id=51 and t2.Id=50
ORDER BY value1.Value