小编Kev*_*vin的帖子

如果至少是负数,则求和;否则就显示

仅当分区中存在负值时,我才需要将值相加。如果分区中没有负值,它应该只输出行。

这就是我现在所拥有的。初始数据作为 CTE 提供。

数据管理语言

;with ledger as (
    select accountId, type, amount
    from (
        values
         (1, 'R', -10)
        ,(1, 'V', 10)
        ,(1, 'R', 30)
        ,(2, 'R', 20)
        ,(2, 'R', -5)
        ,(2, 'V', 5)
        ,(3, 'R', 20)
        ,(3, 'R', 30)
    )   x (accountId, type, amount)
)
,b as ( --identifies accountid, type with negatives
    select
        accountid
        ,type               
    from ledger
    group by accountid, type
    having min(amount) < 0
)
,onlyPositives as (
    select
         l.accountid
        ,l.type
        ,l.amount
    from ledger l
    left join …
Run Code Online (Sandbox Code Playgroud)

sql-server aggregate window-functions group-by sql-server-2016

5
推荐指数
1
解决办法
472
查看次数