MYSQL 根据特定列选择多个列
Posted
技术标签:
【中文标题】MYSQL 根据特定列选择多个列【英文标题】:MYSQL Select multiple columns depending on a specific column 【发布时间】:2017-08-31 00:36:40 【问题描述】:我想做一个 SELECT 请求,根据 PLATFORM 值设法获得 2 列 VALUE(桌面和移动)。
这是一个示例表:
+----+---------+------+----------+-------+
| ID | PROJECT | NAME | PLATFORM | VALUE |
+----+---------+------+----------+-------+
| 1 | 1 | Foo | desktop | 1 |
| 2 | 1 | Foo | mobile | 42 |
| 3 | 1 | Bar | desktop | 3 |
| 4 | 1 | Bar | mobile | 10 |
| 5 | 2 | Foo | desktop | 2 |
| 6 | 2 | Bar | mobile | 9 |
+----+---------+------+----------+-------+
期望的输出:
+---------+------+---------+--------+
| PROJECT | NAME | DESKTOP | MOBILE |
+---------+------+---------+--------+
| 1 | Foo | 1 | 42 |
| 1 | Bar | 3 | 10 |
| 2 | Foo | 2 | NULL |
| 2 | Bar | NULL | 9 |
+---------+------+---------+--------+
我尝试了什么:
SELECT project, name,
(CASE platform WHEN 'desktop' THEN value END) AS "desktop",
(CASE platform WHEN 'mobile' THEN value END) AS "mobile"
FROM test
GROUP BY name, project
ORDER BY project, value ASC
+---------+------+---------+--------+
| project | name | desktop | mobile |
+---------+------+---------+--------+
| 1 | Foo | 1 | NULL |
| 1 | Bar | 3 | NULL |
| 2 | Foo | 2 | NULL |
| 2 | Bar | NULL | 9 |
+---------+------+---------+--------+
【问题讨论】:
你非常接近 :-) 你有什么建议吗? D:@Sebas 【参考方案1】:试试这个:
SELECT project, NAME, MAX(desktop) AS desktop, MAX(mobile) AS mobile FROM (
SELECT project, NAME,
(CASE platform WHEN 'desktop' THEN VALUE END) AS "desktop",
(CASE platform WHEN 'mobile' THEN VALUE END) AS "mobile"
FROM test
) AS aa
GROUP BY aa.NAME, aa.project
ORDER BY aa.project
说明:
首先你对所有数据进行选择(aa),根据平台内容扩展价值。
然后您使用该选择作为分组数据的来源。
结果:
project name desktop mobile
1 Foo 1 42
1 Bar 3 10
2 Foo 2 NULL
2 Bar NULL 9
【讨论】:
以上是关于MYSQL 根据特定列选择多个列的主要内容,如果未能解决你的问题,请参考以下文章