我正在加入两个表,tblAccount和tblInvoice。 TblAccount有多个与每个帐户相关的发票。我正在尝试根据最早的InvoiceDate查询TotalSavings金额,如果同一日期有两个金额值,那么我需要将这两个金额相加。我以为我这样做是正确的,但下面的代码并没有给我所需的输出。
SELECT TA.AccountID,
MIN(TI.InvoiceDate) AS InvoiceDate,
TI.TotalSavings
FROM tblAccount AS TA
LEFT JOIN tblInvoice AS TI
ON TA.AccountID=TI.AccountID
WHERE TI.TotalSavings>0
AND
TI.InvoiceDate IS NOT NULL
GROUP BY TA.AccountID, TI.TotalSavings
ORDER BY TA.AccountID
当我加入两张桌子时,我得到以下结果。
AccountID Invoice Date TotalSavings
ABC 6/30/2012 10
ABC 12/31/2013 20
ABC 6/1/2014 30
BCA 9/30/2011 40
BCA 1/31/2012 50
BCA 11/30/2011 60
CBA 3/1/2015 70
CBA 3/1/2015 80
我正在寻找像这样的输出
AccountID Invoice Date TotalSavings
ABC 6/30/2012 10
BCA 9/30/2011 40
CBA 3/1/2015 150
感谢您在此论坛上提供的任何帮助。
答案 0 :(得分:2)
将joins
与subquery
select a.accountid, s.invoicedate,
sum(s.TotalSavings) as TotalSavings
from tblAccount a
left join tblInvoice s on s.accountid = a.accountid
where s.invoicedate is not null and s.TotalSavings > 0 and
s.invoicedate = (select min(invoicedate)
from tblInvoice
where accountid = a.accountid)
group by a.accountid, s.invoicedate;
您也可以仅使用joins
exists
select accountid, invoicedate, sum(TotalSavings) as TotalSavings
from tblInvoice s
where exists (select 1 from tblAccount where accountid = s.accountid) and
TotalSavings > 0 and
invoicedate = (select min(invoicedate) from tblInvoice where accountid = s.accountid)
group by accountid, invoicedate
答案 1 :(得分:1)
我没有通过模仿像你这样的表来测试下面的代码,但它应该是好的:
; WITH CTE AS (
SELECT TA.AccountID, MIN(TI.InvoiceDate) AS InvoiceDate
FROM tblAccount AS TA
LEFT JOIN tblInvoice AS TI ON TA.AccountID = TI.AccountID -- could be INNER JOIN because you're filtering out the NULL rows on the right with TI.InvoiceDate IS NOT NULL in the WHERE clause
WHERE TI.TotalSavings > 0 AND TI.InvoiceDate IS NOT NULL
)
SELECT c.AccountID, c.InvoiceDate, SUM(i.TotalSavings) AS TotalSavings
FROM CTE c
INNER JOIN tblInvoice i ON c.AccountID = i.AccountID AND c.InvoiceDate = i.InvoiceDate
GROUP BY c.AccountID, c.InvoiceDate;
实际上,您首先必须找到某个帐户(TotalSavings > 0
)节省了一些费用的最低发票日期,然后您必须总结该帐户当天的所有节省。
答案 2 :(得分:1)
根据我的理解,我这样做,您可以使用以下CTE方法。
with
rownumber(id, dateColumn, amt, rn)
as(
select i.id, dateColumn, sum(amt), ROW_NUMBER() OVER(Partition by i.id
ORDER BY dateColumn) rn from tblinvoice i join
tblAccount a on a.id = i.id
group by i.id, dateColumn
)select id, dateColumn, amt from rownumber where rn = 1
--tlbaccount
id
1
2
3
--tlbInvoice --same id with same date. And same id with diff date.
id dateColumn amt
1 2018-04-14 10
1 2018-04-14 20
2 2018-04-14 20
2 2018-03-14 20
--actual O/P --sum amts of same ids with same date and min date from same id with diff date
id dateColumn amt
1 2018-04-14 30
2 2018-03-14 20
答案 3 :(得分:1)
你不需要空或左 杀死左连接的地方 为什么你甚至需要帐户?
select s.accountid, s.invoicedate,
sum(s.TotalSavings) as TotalSavings
from tblInvoice s
where s.TotalSavings > 0
and s.invoicedate = ( select min(invoicedate)
from tblInvoice
where accountid = s.accountid )
group by s.accountid
order by s.accountid;