在选择中使用where或IF SQL求和

时间:2017-04-27 07:58:04

标签: mysql sql

我创建了一个SELECT,如果NIF等于另一个nif并且合约与其他合同相同且产品为100

,我想要'SUM'不同的行
SELECT 
 NIF, 
 CONTRACT, 
 PRODUCT, 
 SUM(SALDO) when PRODUCT=100 
 DATE
from TABLE_AAA

然后我想转换为图表。

NIF     CONTRACT    PRODUCT     SALDO   DATE
1       1001        100           1     27/04/2016
1       1001        100           1     27/04/2016
1       1003        100           2     27/04/2016
1       1003        100           2     27/04/2016
1       1001        102           1     27/04/2016
2       1001        200           5     27/04/2016
2       1001        200           1     27/04/2016

NIF     CONTRACT    PRODUCT     SALDO   DATE
1       1001        100         2       27/04/2016
1       1003        100         4       27/04/2016
1       1001        102         1       27/04/2016
2       1001        200         5       27/04/2016
2       1001        200         1       27/04/2016

5 个答案:

答案 0 :(得分:0)

您需要使用WHERE时,并且在WHERE子句中包含您的其他参数,您还需要GROUP BY。没有样本数据和预期输出,这就是我认为你所追求的。

SELECT 
NIF, 
CONTRACT, 
PRODUCT, 
SUM(SALDO) AS SUMSALDO,
DATE
FROM TABLE_AAA
WHERE PRODUCT = 100
AND CONTRACT = NIF
GROUP BY NIF, CONTRACT, PRODUCT, DATE

好吧也许你的意思是:

SELECT 
NIF, 
CONTRACT, 
PRODUCT, 
SUM(CASE WHEN PRODUCT = 100 AND CONTRACT = NIF THEN SALDO ELSE 0 END) AS SUMSALDO,
DATE
FROM TABLE_AAA
GROUP BY NIF, CONTRACT, PRODUCT, DATE

答案 1 :(得分:0)

这是SQL的sum函数。 SELECT SUM(column_name)FROM table_name;

在你的情况下,

SELECT NIF, CONTRACT, PRODUCT, SUM(SALDO) FROM Table_AAA WHERE PRODUCT = 100 AND NIF = CONTRACT;

我认为这会有所帮助。

答案 2 :(得分:0)

您可以尝试这样的事情:

SELECT 
NIF, 
CONTRACT, 
PRODUCT, 
CASE 
    WHEN (NIF = CONTRACT AND PRODUCT=100)
    THEN
        SUM(SALDO)
    WHEN(otherCondition)
    THEN
        SUM(otherSum)
    ELSE 
        NULL
END
DATE from TABLE_AAA

您可以在How do I use properly CASE..WHEN in MySQLhttps://dev.mysql.com/doc/refman/5.7/en/case.html

的sql中找到有关CASE的更多信息

答案 3 :(得分:0)

如果您想要求和,满足相同条件并且您有多个条件的行,我认为您可以使用以下查询:

SELECT 
 NIF, 
 CONTRACT, 
 PRODUCT, 
 SUM( case when NIF=CONTRACT AND PRODUCT=100 THEN SALDO ELSE 0 END ) SUM_PROD_100 ,
 "DATE"
from TABLE_AAA
GROUP BY NIF, CONTRACT,PRODUCT, "DATE"

您可以使用与“SUM_PROD_100”列相同的逻辑来对满足不同条件的其他行求和。

答案 4 :(得分:0)

您希望实际组合两个查询:

  1. 产品100的汇总行
  2. 其他产品的未更改记录
  3. 所以写两个查询并将两者合并到UNION ALL

    select nif, contract, product, sum(saldo) as saldo, max(date) as date
    from table_aaa
    where product = 100
    group by nif, contract, product
    union all
    select nif, contract, product, saldo, date
    from table_aaa
    where product <> 100
    order by nif, contract, product, date;