【问题标题】:SQL: How to find the sum of values where all the records has the same value in a column?SQL:如何找到列中所有记录具有相同值的值的总和?
【发布时间】:2015-08-26 12:16:45
【问题描述】:

我的 Payments 表包含多个列,包括 Student、 ValuePayment_type。 我想创建一个查询来计算值的总和,如果同一学生的所有记录只有 NULL 作为付款类型。 如果学生至少有一种不同于 NULL 的付款类型,则不应包括该学生。

例子:

Student      Payment      Value      Payment_type
   1            1          100         NULL
   1            2          200         NULL
   2            1          200         NULL
   3            1          150         Cash
   2            2          100         Cash
   3            2          200         NULL
   1            3          200         NULL

如果你看这个例子,它应该给我结果 500,因为学生 1 的值总和是 500,他/她的所有付款类型都是 NULL。

【问题讨论】:

  • 您使用的是哪个 DBMS?后格雷斯?甲骨文?

标签: sql select where


【解决方案1】:

SQL Fiddle

MySQL 5.6 架构设置

CREATE TABLE Payments 
    (`Student` int, `Payment` int, `Value` int, `Payment_type` varchar(4))
;

INSERT INTO Payments 
    (`Student`, `Payment`, `Value`, `Payment_type`)
VALUES
    (1, 1, 100, NULL),
    (1, 2, 200, NULL),
    (2, 1, 200, NULL),
    (3, 1, 150, 'Cash'),
    (2, 2, 100, 'Cash'),
    (3, 2, 200, NULL),
    (1, 3, 200, NULL)
;

查询 1

select student, sum(value)
from payments
group by student
having max(Payment_type) IS NULL

Results

| Student | sum(value) |
|---------|------------|
|       1 |        500 |

【讨论】:

    【解决方案2】:
    select student, sum(value)
    from payments
    group by student
    having sum(case when Payment_type is not null then 1 else 0 end) = 0
    

    【讨论】:

    • 成功了,谢谢。如果我想再添加一个过滤条件,比如 Where Year=2015 ??
    • 然后只需添加where 子句即可仅查看当年的记录。
    【解决方案3】:

    这应该可行:

    select 
        student, sum(value)
    from 
        payments
    group by 
        student
    having sum
       (case when Payment_type is not null then 1 else 0 end) = 0
    

    【讨论】:

      【解决方案4】:

      对我来说,这是非常干净的,而且你的描述在语义上是准确的:

        SELECT student, SUM(value)
          FROM payments p1
         WHERE NOT EXISTS (SELECT 1
                             FROM payments p2
                            WHERE p2.student = p1.student
                              AND Payment_type IS NOT NULL)
      GROUP BY student
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 2013-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多