2015-03-03 69 views
0

我有5个表:最近的日期和价格从SQL Server中的多个表

​​

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(在contracts_anexes表多行)

例如

  • id_contract = 1我需要返回的价格300和日期2014 -06-05,
  • id_contract = 2我需要回到400的价格及日期2015-01-12
  • id_contract = 3我需要回到300的价格和日期2014年10月12日
+1

添加您尝试的样本数据和预期结果以及查询。这个问题非常令人困惑,因为有两个带有'price'的表格和两个带有'date_sign'的表格 – 2015-03-03 07:29:50

+0

如果最近的'date_sign'在'anexes_data'中,但最高价格在'contracts_data'中怎么办? – 2015-03-03 07:52:52

+0

@wewesthemenace没有提到最高价格,只是最近的日期。 – philipxy 2015-03-03 07:54:21

回答

1

您可以用ROW_NUMBER一起使用UNION ALL

;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

+0

很好,谢谢! – user1762186 2015-03-03 08:15:06

相关问题