合并两个视图

时间:2012-09-27 07:35:57

标签: sql sql-server-2008

我有两个视图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

2 个答案:

答案 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 

SQLFiddle Demo

答案 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

SQL FIDDLE DEMO

如果符合条件,则只会将B值替换为A值。


<强> EDIT2

添加

    ORDER BY
              sFeeToBePaid DESC
            , SchoolStudentID
在这种特定情况下,

会给你你想要的订单。然而,这似乎并不合理。我需要知道B中所需的行顺序,以保持顺序一致。

请注意,如果未指定ORDER BY,则查询引擎会根据其认为合适的顺序来确认请求。这通常可以在呼叫之间保持一致,但这只是偶然的。如果您的服务器具有多个处理器,并且查询性能可以从使用多个处理器中获益,那么您会注意到频繁的变化。即如果您的查询计划涉及并行化。