2

我有两个视图 A 和 B 都具有相同的列名StudentID, FeeToBePaid, AmountPaid。在这两种观点StudentID中是相同的。但列FeeToBePaidAmountPaid是不同的。

我想将 B 中的行替换为 Aif 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
4

2 回答 2

2

尝试通过结合两个LEFT JOINusing UNIONwithout ALL的结果来消除重复记录。

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 

SQLFiddle 演示

于 2012-09-27T08:05:42.757 回答
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

SQL 小提琴演示

如果满足条件,这只是用值替换B值。A


编辑2

添加

    ORDER BY
              sFeeToBePaid DESC
            , SchoolStudentID

在这种特定情况下会给你你想要的订单。然而,这似乎并不明智。我需要知道所需的行顺序B以保持顺序一致。

请注意,如果没有ORDER BY指定,查询引擎将使用它认为合适的任何顺序来统计请求。这可能在调用之间通常是一致的,但这只是偶然的。如果您的服务器有多个处理器并且查询性能受益于使用多个处理器,您会注意到频繁的变化。即,如果您的查询计划涉及并行化。

于 2012-09-27T08:04:12.007 回答