SQL Server中多个表的最新日期和价格

时间:2015-03-03 07:28:14

标签: sql-server max

我有5张桌子:

contracts, contracts_data, contracts_anexes, anexes, anexes_data

contracts列:

id_contract |  date_sign
------------+-----------
    1       | 2013-01-03
    2       | 2013-06-05
    3       | 2014-10-12

contracts_data列:

id_contract | price
------------+------
     1      | 100
     2      | 200
     3      | 300

uontracts_anexes列:

id_contract | id_anex
------------+--------
    1       |    1
    1       |    2
    2       |    3

anexes列:

id_anex | date_of_sign 
--------+--------------
   1    | 2014-01-03
   2    | 2014-06-05
   3    | 2015-01-12

anexes_Data列:

id_anex | price
--------+------
   1    | 200
   2    | 300
   3    | 400

现在我需要选择价格(来自contracts_dataanexes_data),其中签名日期最近(date_sign来自contractsanexes ),但并非所有id_contract都在表contracts_anexes中(并非所有合同都有附件),一个合同(id_contract)可能有多个anexes({ {1}}表)

例如

  • for contracts_anexes我需要返回价格300和日期2014-06-05,
  • for id_contract = 1我需要返回价格400和日期2015-01-12
  • for id_contract = 2我需要返回价格300和日期2014-10-12

1 个答案:

答案 0 :(得分:1)

您可以将UNION ALLROW_NUMBER一起使用:

;WITH CteUnion AS(
    SELECT
        id_contract = c.id_contract,
        price = cd.price,
        date_sign = c.date_sign
    FROM contracts c
    LEFT JOIN contracts_data cd
        ON cd.id_contract = c.id_contract

    UNION ALL

    SELECT
        id_contract = c.id_contract,
        price = ad.price,
        date_sign = a.date_sign
    FROM contracts c
    LEFT JOIN contracts_anexes ca
        ON ca.id_contract = c.id_contract
    LEFT JOIN anexes a
        ON a.id_anex = ca.id_anex
    LEFT JOIN anexes_data ad
        ON ad.id_anex = a.id_anex
)
SELECT
    id_contract,
    price,
    date_sign
FROM(
    SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY id_contract ORDER BY date_sign DESC)
    FROM CteUnion
)c
WHERE RN = 1

请参阅 SQL Fiddle