如果summ为正+
,则表示帐户拥有资金,如果记录为负-
,则表示帐户有付款。
我需要找出今天哪个帐户没有任何资金,我有这个问题:
SELECT a.Customer
,a.Deal
,(a.positive + b.negative) AS own_to_the_bank
FROM (
SELECT SUM(Summ) AS positive
,Customer
,Deal
FROM #test
WHERE Summ > 0
GROUP BY Customer
,Deal
) AS a
JOIN (
SELECT SUM(Summ) AS negative
,Customer
,Deal
FROM #test
WHERE Summ < 0
GROUP BY Customer
,Deal
) AS b ON a.Customer = b.Customer
AND a.Deal = b.Deal
WHERE a.positive + b.negative >0
及其工作正常,所以现在我必须找出当我的查询a.positive + b.negative = 0
时帐户停止向银行取款的时候。
坚持这个问题几个小时,任何帮助?
答案 0 :(得分:1)
我开始创建每日余额,客户,交易和货币
SELECT t1.Customer, t1.Deal, t1.Currency, t1.Date, Balance = (SELECT SUM(Summ) FROM #test as hist WHERE hist.Customer = t1.Customer and hist.Deal = t1.Deal and hist.Currency = t1.Currency and hist.Date <= t1.Date)
FROM #test as t1
添加了正余额和rownum条件(按日期排序)
SELECT Customer, Deal, Currency, Date, Balance, RowNum = ROW_NUMBER() OVER(PARTITION BY Customer, Deal, Currency ORDER BY Date)
FROM
(
select t1.Customer, t1.Deal, t1.Currency, t1.Date, Balance = (SELECT SUM(Summ) FROM #test as hist WHERE hist.Customer = t1.Customer and hist.Deal = t1.Deal and hist.Currency = t1.Currency and hist.Date <= t1.Date)
FROM #test as t1
) as inn
WHERE Balance > 0
最后选了第一个。
SELECT Customer, Deal, Currency, Date, Balance
FROM ( SELECT Customer, Deal, Currency, Date, Balance, RowNum = ROW_NUMBER() OVER(PARTITION BY Customer, Deal, Currency ORDER BY Date)
FROM
(
SELECT t1.Customer, t1.Deal, t1.Currency, t1.Date, Balance = (SELECT SUM(Summ) FROM #test as hist WHERE hist.Customer = t1.Customer and hist.Deal = t1.Deal and hist.Currency = t1.Currency and hist.Date <= t1.Date)
FROM #test as t1
) as t
WHERE Balance > 0 ) as t2
WHERE t2.RowNum = 1
答案 1 :(得分:-1)
当客户停止时,您可能会有几个日期
例如,我们有两个日期:
+1000
+500
-500
+500
-500
此查询显示最后一个:
select distinct a.customer, a.date
from test as a
left join test as b
on a.Date > b.Date and a.Customer = b.Customer
where a.summ < 0 and b.summ > 0
group by a.customer order by a.date, b.date desc
线索是按日期在不同方向订购连接表,然后按每个客户的第一行排序。