我有桌子
+---------------------+
| ID | Code | Amount -|
+---------------------+
| 1 | 101 | 1.2 |
| 1 | 102 | 1.3 |
| 1 | 103 | 1.3 |
| 1 | 104 | 1.4 |
| 1 | 105 | 1.2 |
| 2 | 101 | 1.5 |
| 2 | 102 | 1.4 |
| 2 | 103 | 1.3 |
| 2 | 104 | 1.1 |
| 2 | 105 | 1.0 |
+---------------------+
我要做的是将每个不是代码101的ID的金额列更改为代码101中的金额值
所以我的输出应该是这样的。
+---------------------+
| ID | Code | Amount -|
+---------------------+
| 1 | 101 | 1.2 |
| 1 | 102 | 1.2 |
| 1 | 103 | 1.2 |
| 1 | 104 | 1.2 |
| 1 | 105 | 1.2 |
| 2 | 101 | 1.5 |
| 2 | 102 | 1.5 |
| 2 | 103 | 1.5 |
| 2 | 104 | 1.5 |
| 2 | 105 | 1.5 |
+---------------------+
这显然是一个简化的表格,可以显示我需要的东西,因为今天的行数超过100,000,但每天都会改变。
我试过使用游标,但速度很慢。反正有吗?
由于
答案 0 :(得分:2)
update t
set t.amount = t2.amount
from your_table t
join
(
select id, min(amount) as amont
from your_table
where code = 101
group by id
) t2 on t1.id = t2.id
where t.code <> 101
答案 1 :(得分:1)
这样可以解决问题:
DECLARE @t table(ID int, Code int, Amount decimal(6,1))
INSERT @t values
(1,101,1.2),(1,102,1.3),
(1,103,1.3),(1,104,1.4),
(1,105,1.2),(2,101,1.5),
(2,102,1.4),(2,103,1.3),
(2,104,1.1),(2,105,1.0)
;WITH CTE AS
(
SELECT
min(CASE WHEN Code = 101 THEN amount end)
over (partition by ID) newAmount,
Code,
Amount
FROM @t
)
UPDATE CTE
SET Amount = newAmount
WHERE
code <> 101
AND newAmount is not NULL
SELECT * FROM @t
结果:
ID Code Amount
1 101 1.2
1 102 1.2
1 103 1.2
1 104 1.2
1 105 1.2
2 101 1.5
2 102 1.5
2 103 1.5
2 104 1.5
2 105 1.5
答案 2 :(得分:0)
您可以像这样使用UPDATE FROM
UPDATE Tbl1
SET Amount = Tbl2.Amount
FROM Tbl1
INNER JOIN
(
SELECT ID,Code,Amount
FROM Tbl1
WHERE Code = 101
)Tbl2
ON Tbl1.ID = Tbl2.ID
WHERE Tbl1.Code <> 101;
修改强>
如果相同的代码和ID可以有多个金额值,GROUP BY
可以像这样使用。
UPDATE Tbl1
SET Amount = Tbl2.Amount
FROM Tbl1
INNER JOIN
(
SELECT ID,MAX(Amount) as Amount
FROM Tbl1
WHERE Code = 101
GROUP BY ID
)Tbl2
ON Tbl1.ID = Tbl2.ID
WHERE Tbl1.Code <> 101;
答案 3 :(得分:-1)
example.controller("Ctrl", function($scope) {
$scope.truck = "Truck Value";
});
修改强>
检查
Update YourTable
Set Amount = (select top 1 a.amount from yourtable a where a.id = YourTable.id and a.code = 101)
答案 4 :(得分:-1)
使用子查询获取id:
的101金额update tablename t1 set amount = (select max(amount) from tablename t2
where t1.ID = t2.id
and t2.code = 101)
where t1.code <> 101;
无需更新101行,使其不在交易中(where t1.code <> 101
)。
MAX(amount)
用于确保只从子查询返回一行。