SQL: 如何找到列中所有记录具有相同值的值的总和?

SQL: How to find the sum of values where all the records has the same value in a column?

我有多个列的 Payments table,包括 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,并且 his/her 所有支付类型都是 NULL。

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

这应该有效:

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

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 |

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

  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