我有两个视图A和B都具有相同的列名StudentID, FeeToBePaid, AmountPaid
。在两个视图中StudentID
都是相同的。但是FeeToBePaid
列和AmountPaid
列不同。
我想将A中的行替换为来自A if A.FeeToBePaid <= A.AmountPaid
的行与studentID
相同。
查看A
SchoolStudentID sFeeToBePaid amountpaid
12-S-3003 1000.00 1000.00
查看B
SchoolStudentID sFeeToBePaid amountpaid
12-S-3003 1000.00 0.00
11-F-2019 NULL 1000.00
12-S-3009 NULL 1000.00
我需要答案
SchoolStudentID
sFeeToBePaid
amountpaid
12-S-3003 1000.00 1000.00
11-F-2019 NULL 1000.00
12-S-3009 NULL 1000.00
答案 0 :(得分:2)
通过使用LEFT JOIN
而不使用 ALL 组合两个UNION
的结果来尝试,以消除重复记录。
SELECT a.SchoolStudentID ,
CASE WHEN a.sFeeToBePaid <= a.amountpaid
THEN a.sFeeToBePaid
ELSE b. sFeeToBePaid
END AS sFeeToBePaid,
CASE WHEN a.sFeeToBePaid <= a.amountpaid
THEN a.amountpaid
ELSE b.amountpaid
END AS amountpaid
FROM ViewA a
LEFT JOIN ViewB b
ON a.SchoolStudentID = b.SchoolStudentID
UNION
SELECT a.SchoolStudentID ,
CASE WHEN b.sFeeToBePaid <= b.amountpaid
THEN b.sFeeToBePaid
ELSE a. sFeeToBePaid
END AS sFeeToBePaid,
CASE WHEN b.sFeeToBePaid <= b.amountpaid
THEN b.amountpaid
ELSE a.amountpaid
END AS amountpaid
FROM ViewB a
LEFT JOIN ViewA b
ON a.SchoolStudentID = b.SchoolStudentID
答案 1 :(得分:1)
修改强>
考虑到,任何UNION
都是不必要的,以下就足够了
SELECT
B.SchoolStudentID
, CASE WHEN(A.sFeeToBePaid <= A.amountpaid)
THEN A.sFeeToBePaid
ELSE B.sFeeToBePaid
END sFeeToBePaid
, CASE WHEN(A.sFeeToBePaid <= A.amountpaid)
THEN A.amountpaid
ELSE B.amountpaid
END amountpaid
FROM
B
LEFT JOIN
A ON A.SchoolStudentID = B.SchoolStudentID
如果符合条件,则只会将B
值替换为A
值。
<强> EDIT2 强>
添加
ORDER BY
sFeeToBePaid DESC
, SchoolStudentID
在这种特定情况下,会给你你想要的订单。然而,这似乎并不合理。我需要知道B
中所需的行顺序,以保持顺序一致。
请注意,如果未指定ORDER BY
,则查询引擎会根据其认为合适的顺序来确认请求。这通常可以在呼叫之间保持一致,但这只是偶然的。如果您的服务器具有多个处理器,并且查询性能可以从使用多个处理器中获益,那么您会注意到频繁的变化。即如果您的查询计划涉及并行化。