根据匹配指定标准的子记录计数选择记录

时间:2015-02-03 22:15:23

标签: sql-server

我在SQL 08数据库中有两个表:

  • 客户
  • 天平
    • ClientID(客户端的外键)
    • isStartingBalance(bit)

使用SQL,我需要找到并更新所有余额记录,其中平衡记录所属的客户只有一个余额记录,而该余额记录的isStartingBalance = 0。我需要更新这些记录,以便isStartingBalance = 1。

我该怎么做呢?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用子查询查找只有一个余额行的客户:

update  Balances
set     isStartingBalance = 1
where   isStartingBalance = 0
        and ClientID in
        (
        select  ClientID
        from    Balances
        group by
                ClientID
        having  count(*) = 1
        )

或者更明智的是,您可以为每个客户更新最旧的余额行:

update  bal
set     isStartingBalance = 1
from    (
        select  row_number() over (
                    partition by ClientID 
                    order by dt) as rn
        ,       *
        from    Balance
        ) bal
where   rn = 1
        and isStartingBalance = 0

Example at SQL Fiddle.

更明智的解决方案是完全删除isStartingBalance列,并在需要时进行查询:

select  ClientID
,       dt
,       case when rn = 1 then 1 else 0 end as isStartingBalance
from    (
        select  ClientID
        ,       dt
        ,       row_number() over (
                    partition by ClientID
                    order by dt) as rn
        from    Balance
        ) SubQueryAlias