我有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_data
或anexes_data
),其中签名日期最近(date_sign
来自contracts
和anexes
),但并非所有id_contract
都在表contracts_anexes
中(并非所有合同都有附件),一个合同(id_contract
)可能有多个anexes
({ {1}}表)
例如
contracts_anexes
我需要返回价格300和日期2014-06-05,id_contract = 1
我需要返回价格400和日期2015-01-12 id_contract = 2
我需要返回价格300和日期2014-10-12 答案 0 :(得分:1)
您可以将UNION ALL
与ROW_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 。