我的问题是我想知道如何编写一个sql语句,将余额超过10,0000美元的所有账户增加6%,所有其他账户获得5%(不使用CASE语句) 该表中涉及的表是包含以下字段的帐户表: (account_number(PK),branch_name,balance)。 提前谢谢......
答案 0 :(得分:6)
只是为了好玩,这个版本的ypercube脚本只有1个更新,应该可以完成这个任务:
UPDATE tableX
SET balance = balance * (1 + ((5.00 + convert(bit,floor(balance/10000))) / 100))
注意:我使用5.00强制除法成小数,而不是作为int舍入。您也可以通过正确执行并转换为小数来执行此操作。
答案 1 :(得分:4)
我想知道为什么不能使用CASE
。无论如何:
UPDATE tableX
SET balance = balance * (1 + 0.06)
WHERE balance > 10000 ;
UPDATE tableX
SET balance = balance * (1 + 0.05)
WHERE balance <= 10000
AND balance > 0 ;
你可能想把它放在一个交易中。
不使用CASE
且只使用一个UPDATE
:
UPDATE x
SET x.balance = x.balance * (1 + y.raise/100)
FROM tableX AS x
JOIN
( SELECT 0 AS low, 10000 AS high, 5.0 AS raise
UNION
SELECT 10000, 9999999999, 6.0
) AS y
ON x.balance > y.low
AND x.balance <= y.high
还有一种方法,只是为了好玩:
UPDATE tableX AS x
SET balance = balance *
( SELECT TOP 1
change
FROM
( SELECT 0 AS low, 1.05 AS change
UNION
SELECT 10000, 1.06
) AS y
WHERE balance > low
ORDER BY low DESC
)
WHERE balance > 0
答案 2 :(得分:3)
或此查询:)),但比Jon的查询更加苛刻。
update tableX a set ballance =
(select ballance*(1+6/100) as ballance_new
from tableX b
where ballance >=10000 and b.account_name = a.account_name
union all
select ballance*(1+5/100) as ballance_new c
from tableX
where ballance <10000 and c.account_name = a.account_name)
答案 3 :(得分:1)
我认为还有一个简单的解决方案。这是:
UPDATE @t
SET balance = (SELECT balance* 1.05 where balance <= 10000
UNION SELECT balance* 1.06 where balance > 10000)
修改后的@ AndriyM使用UNION ALL代替UNION以获得更好的性能
UPDATE @t
SET balance = (SELECT balance* 1.05 where balance <= 10000
UNION ALL SELECT balance* 1.06 where balance > 10000)