动态SQL JOIN而不是UNION

时间:2015-03-30 18:06:34

标签: sql sql-server

我目前有以下查询(实际代码的小片段),其中我多次执行UNION ALL SELECT,因为订单可能会有1到5个与之相关的贷款。但是,我不知道如何使用UNION ALL而只调整LoanOrder三次,我想知道如何(如果可能的话)动态引入LoanOrder?这样,如果实际上只有一个贷款与订单相关联,我就不再运行两个SELECT语句。虽然我目前的方法有效,但我只是想为我未来的努力更好地优化和学习新的东西。提前谢谢!

SELECT DISTINCT
    -- 1st Loan Premiums
    L.LoanOrder
    ,'Loan Premium' AS 'Type'
    ,'Policies:' AS 'Type1'
FROM
    Orders O
    LEFT JOIN Loan L
        ON O.OrdersID = L.OrdersID
        AND L.LoanOrder = 1
UNION ALL
SELECT DISTINCT
    -- 2nd Loan Premiums
    L.LoanOrder
    ,'Loan Premium' AS 'Type'
    ,'Policies:' AS 'Type1'
FROM
    Orders O
    LEFT JOIN Loan L
        ON O.OrdersID = L.OrdersID
        AND L.LoanOrder = 2
UNION ALL
SELECT DISTINCT
    -- 3rd Loan Premiums
    L.LoanOrder
    ,'Loan Premium' AS 'Type'
    ,'Policies:' AS 'Type1'
FROM
    Orders O
    LEFT JOIN Loan L
        ON O.OrdersID = L.OrdersID
        AND L.LoanOrder = 3
UNION ALL
SELECT DISTINCT
    -- 4th Loan Premiums
    L.LoanOrder
    ,'Loan Premium' AS 'Type'
    ,'Policies:' AS 'Type1'
FROM
    Orders O
    LEFT JOIN Loan L
        ON O.OrdersID = L.OrdersID
        AND L.LoanOrder = 4
UNION ALL
SELECT DISTINCT
    -- 5th Loan Premiums
    L.LoanOrder
    ,'Loan Premium' AS 'Type'
    ,'Policies:' AS 'Type1'
FROM
    Orders O
    LEFT JOIN Loan L
        ON O.OrdersID = L.OrdersID
        AND L.LoanOrder = 5

2 个答案:

答案 0 :(得分:4)

您似乎根本没有使用Orders表。所以,我认为您查询的更简单版本是:

SELECT L.LoanOrder, 'Loan Premium' AS 'Type', 'Policies:' AS 'Type1'
FROM Loan L
WHERE L.LoanOrder IN (1, 2, 3, 4, 5);

您可能正在使用orders进行过滤,但这似乎不太可能。

我还删除了distinct - 理由是它可能是不必要的。如果LoanOrder可以出现在Loan的多行中,那么您可能需要它。

编辑:

如果确实需要Orders

SELECT DISTINCT L.LoanOrder, 'Loan Premium' AS 'Type', 'Policies:' AS 'Type1'
FROM Orders o LEFT JOIN
     Loan L
     ON O.OrdersID = L.OrdersID AND
        L.LoanOrder IN (1, 2, 3, 4, 5);

答案 1 :(得分:2)

有什么问题
SELECT DISTINCT
    L.LoanOrder
    ,'Loan Premium' AS 'Type'
    ,'Policies:' AS 'Type1'
FROM
  Orders O
  LEFT JOIN Loan 
    ON O.OrdersID = L.OrdersID
      AND L.LoanOrder > 0
      AND L.LoanOrder < 6