SQL求和值对 [英] SQL sum pairs of values

查看:75
本文介绍了SQL求和值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是SQL的新手,我不知道该怎么做.我想对一个类似的对(vin,action)求和一个名为"total_spending"的汇总,并选择第一个Dealer_name和参考月份年份(这样它就不会创建重复项),并具有类似示例的输出:输入

I'm new to SQL and I couldn't figure how to do this. I would like to sum a coulmn called "total_spending" for similar pairs (vin, action) and choose the first dealer_name and reference month year (so it won't create duplicates) and have an output like the example: Input

action  dealer_name   vin    Total_spending reference month year 
A1      D1            V1         T1             R1     M1    Y1
A2      D2            V2         T2             R1     M1    Y1
A2      D2            V2         T3             R2     M2    Y2
A3      D2            V1         T4             R1     M1    Y1
A4      D1            V2         T5             R1     M1    Y1
A2      D1            V2         T6             R1     M1    Y1
A1      D1            V1         T7             R2     M2    Y2
A4      D1            V2         T8             R2     M2    Y2
A1      D1            V1         T9             R3     M3    Y3
A3      D2            V2         T10            R1     M1    Y1
A3      D2            V1         T11            R2     M2    Y2

输出

action  dealer_name   vin    Total_spending reference month year 
A1      D1            V1         T1 + T7 + T9   R1     M1    Y1
A2      D2            V2         T2 + T3        R1     M1    Y1
A3      D2            V1         T4 + T11       R1     M1    Y1
A4      D1            V2         T5 + T8        R1     M1    Y1
A2      D1            V2         T6             R1     M1    Y1
A3      D2            V2         T10            R1     M1    Y1


    SELECT
        action,
        dealer_name,
        vin,
        SUM(total_spending) as total_spending,
        reference,
        year,
        issue_date,
        country_code
    FROM
        db_raw_irn_67634_vdt.sap_vme_pol
    GROUP BY
        action,
        dealer_name,
        vin,
        reference,
        year,
        issue_date,
        country_code

推荐答案

SELECT action
    ,dealer_name
    ,vin
    ,SUM(total_spending)
    ,MIN(reference)
    ,MIN(month)
    ,MIN(YEAR)
FROM db_raw_irn_67634_vdt.sap_vme_pol
GROUP BY action
    ,dealer_name
    ,vin

这篇关于SQL求和值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆