MYSQL根据特定列选择多个列

时间:2017-04-05 11:55:17

标签: mysql select merge group-by nested-select

我想做一个SELECT请求,根据PLATFORM值,设法获得2列VALUE(DESKTOP& MOBILE)。

以下是一个示例表:

$(document).ready(function () {
$(window).scroll(function() {
var windowBottom = $(this).scrollTop() + $(this).innerHeight();
$(".fade").each(function() { 
  /* .fade{opacity:0;} in css, Check the location of each desired element */
  var objectBottom = $(this).offset().top + $(this).outerHeight();

  /* If the element is completely within bounds of the window, fade it in */
  if (objectBottom < windowBottom) { //object comes into view (scrolling down)
    if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}} else { //object goes out of view (scrolling up)
    if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}
}
});
}).scroll(); //invoke scroll-handler on page-load
});

期望的输出:

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

1 个答案:

答案 0 :(得分:3)

试试这个:

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