我有一个返回不同记录的SQL查询
select distinct
VENDOR_NUMBER,VENDOR_NAME,CHECK_DATE,
EMAIL_ADDRESS,FAX,check_amount
from MOF_AP_REMITTANCE_GFOS_HEADER_HISTORY
where VENDOR_NUMBER = 4382501 and DATEPART(yy, CHECK_DATE) = '2015'
4382501 | Zayani | 2015-01-15 | xx@bb.com | NULL | 1460.000
4382501 | Zayani | 2015-01-29 | xx@bb.com | NULL | 5556.000
4382501 | Zayani | 2015-02-15 | xx@bb.com | NULL | **730.000**
4382501 | Zayani | 2015-02-15 | xx@bb.com | NULL | **11781.000**
如果我有多条记录,我需要得到每条记录的总和
我需要结果看起来像下面的
4382501 | Zayani | 2015-01-15 | xx@bb.com | NULL | 1460.000
4382501 | Zayani | 2015-01-29 | xx@bb.com | NULL | 5556.000
4382501 | Zayani | 2015-02-15 | xx@bb.com | NULL | **12511.000**
我尝试使用SUM函数,但由于DB中的数据看起来像这样,我得到了错误的结果
4382501 | Zayani | 2015-01-15 | xx@bb.com | NULL | 1460.000
4382501 | Zayani | 2015-01-15 | xx@bb.com | NULL | 1460.000
4382501 | Zayani | 2015-01-29 | xx@bb.com | NULL | 5556.000
4382501 | Zayani | 2015-02-15 | xx@bb.com | NULL | **730.000**
4382501 | Zayani | 2015-02-15 | xx@bb.com | NULL | **11781.000**
如果你能看到第二条记录是重复的那就是为什么我使用了不同的
任何建议?
答案 0 :(得分:1)
使用GROUP BY
和SUM
:
select VENDOR_NUMBER,VENDOR_NAME,CHECK_DATE,
EMAIL_ADDRESS,FAX,SUM(check_amount ) as check_amount
from (select distinct
VENDOR_NUMBER,VENDOR_NAME,CHECK_DATE,
EMAIL_ADDRESS,FAX,check_amount
from MOF_AP_REMITTANCE_GFOS_HEADER_HISTORY
where VENDOR_NUMBER = 4382501 and DATEPART(yy, CHECK_DATE) = '2015'))
GROUP BY VENDOR_NUMBER,VENDOR_NAME,CHECK_DATE,EMAIL_ADDRESS,FAX