SQL:如何选择多个共享“ NAME”字段的COUNT个值?

时间:2019-03-23 23:05:41

标签: sql derby

我有一个名为STUDENTS的APACHE DERBY数据库表,其中包含以下行:

_____________________________
| NAME  |COUNTER|   MONTH   |
-----------------------------
| bill  |   10  |   January |
-----------------------------
| bill  |   12  |   February|
-----------------------------
| bill  |   11  |   March   |
-----------------------------
| sam   |   14  |   January |
-----------------------------
| sam   |   9   |   February|
-----------------------------
| sam   |   22  |   March   |
-----------------------------
| hal   |   21  |   January |
-----------------------------
| hal   |   18  |   February|
-----------------------------
| hal   |   19  |   March   |
-----------------------------

我正在尝试查找语法以获取以下输出...

_________________________________
| NAME  |  JAN  |  FEB  |   MAR |
---------------------------------
| bill  |  10   |  12   |  11   |
---------------------------------
| sam   |  14   |   9   |  22   |
---------------------------------
| hal   |  21   |  18   |  19   |
---------------------------------

我尝试了以下操作:

select distinct(name), 
    (SELECT COUNTER FROM STUDENTS WHERE NAME = 'bill' AND month = 'january') as jan,
    (SELECT COUNTER FROM STUDENTS WHERE NAME = 'bill' AND month = 'february') as feb,
    (SELECT COUNTER FROM STUDENTS WHERE NAME = 'bill' AND month = 'march') as mar
    FROM STUDENT where name = 'bill'

...并且它可以作为一个学生的概念证明。但是,它比较罗,,仅适用于一名学生,并且无法缩放来自 未来几个月,我将添加到数据库中。这意味着,无论数据库中有多少个月的数据退出,我都希望能够仅获取每个NAME的最后3个COUNTER值。

我看过多个s.o。与嵌套查询有关的问题,但没有一个有帮助。

建议?

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

您可以使用条件聚合

SELECT name,
       Max(CASE WHEN month = 'January'  THEN counter end) AS jan,
       Max(CASE WHEN month = 'February' THEN counter end) AS feb,
       Max(CASE WHEN month = 'March'    THEN counter end) AS mar
  FROM student
 GROUP BY name