SQL查询选择范围

时间:2013-09-16 20:49:40

标签: sql select

我有一张这样的桌子......

+---------+------------+------+-------+
|  City   | NamePeople | Age  | Money |
+---------+------------+------+-------+
| Paris   | John       |  10  |  200  |
| London  |  Marie     |  21  |  300  |
| Paris   |  Kevin     |  50  |  250  |
| Paris   |  Julia     |  45  |  150  |
+---------+------------+------+-------+

我需要一个带范围的结果,类似这样的

+---------------+------------+-----------------------+-------------------------+
|      City     | Sum(Money) | CountPeopleWithAge<30 | CountPeopleWithAge>30   |
+---------------+------------+-----------------------+-------------------------+
|   Paris       |       600  |                    1  |                      2  |
|   London      |       300  |                    1  |                      0  |
+---------------+------------+-----------------------+-------------------------+

如何使用sql select?

执行此操作

感谢。

2 个答案:

答案 0 :(得分:4)

Select
    City,
    Sum(Money),
    Sum(Case When Age < 30 Then 1 Else 0 End),
    Sum(Case When Age > 30 Then 1 Else 0 End)
From
    table
Group By
    City

答案 1 :(得分:0)

您可以使用此查询

SELECT City, 
    SUM(Money), 
   SUM(case when Age < 30 then 1 else 0 end),
   SUM(case when Age > 30 then 1 else 0 end)
FROM tableA
GROUP BY City