【问题标题】:SQL query select with rangesSQL查询选择范围
【发布时间】:2013-09-21 03:18:21
【问题描述】:

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

+---------+------------+------+-------+
|  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 执行此操作?

谢谢。

【问题讨论】:

  • 请附上您尝试过的代码以及出了什么问题。 Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results.
  • 年龄正好是 30 岁的人呢?
  • @Laurence 我认为预期的输出还有一些问题sqlfiddle.com/#!3/d964b/2
  • @ConradFrix 也修复了这些问题,谢谢

标签: sql select


【解决方案1】:
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

【讨论】:

  • 劳伦斯的回答看起来最好,但不要忘记正好 30 岁的人。
【解决方案2】:

您可以使用此查询,

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

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多