我的条件加入

时间:2018-03-27 13:31:57

标签: sql join sql-server-2012

我的SQL请求有问题,如果我有2个结果,我需要fr05的结果,只有这一个。

SELECT sad.*, pl.*
FROM SalesAndDistrib AS sad 
INNER JOIN Price_List AS pl ON pl.VKORGAU = sad.VBAK_VKORG 
                            AND sad.VBAP_MATNR = pl.MATNR 
                            AND pl.WERKS in ('FR27', 'FR05')

我无法妥善解决这个问题。 谢谢您的帮助 最诚挚的问候

2 个答案:

答案 0 :(得分:0)

这是所有未经测试的代码,因为我需要一个数据集来对其进行运行。

SELECT * 
FROM   (SELECT sad.*, 
               pl.*, 
               Row_number() 
                 OVER( 
                   partition BY vbap_matnr 
                   ORDER BY PL.werks ASC) AS row_num 
        FROM   salesanddistrib AS sad 
        INNER JOIN price_list AS pl 
                ON pl.vkorgau = sad.vbak_vkorg 
               AND sad.vbap_matnr = pl.matnr 
               AND pl.werks IN ( 'FR27', 'FR05' )) AS bob 
WHERE  bob.row_num = 1 

这样做是使用github按照pl.werks对所有记录进行分组。 然后选择前1 应该给你fr05记录,因为fr05在fr27之前出现

答案 1 :(得分:0)

我认为以下内容相当普遍。

select top (1) sad.*, pl.*
FROM  SalesAndDistrib AS sad 
INNER JOIN Price_List AS pl 
ON pl.VKORGAU = sad.VBAK_VKORG 
AND sad.VBAP_MATNR = pl.MATNR and pl.WERKS in ('FR27','FR05')
Order by pl.werks. --add asc or desc as required