如何防止左连接返回多行

时间:2020-12-23 13:35:26

标签: sas

在 SAS 中使用左连接时,右侧表有重复的 ID,不同的捐赠。因此,它返回几行。 而我只想要捐赠金额最高的一行。

代码如下:

Create table x
As select T1.*,
T2. Donations

From xxx t1
Left join yy t2 on (t1.id = t2.id);
Quit;

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

在 SAS 中跟随 https://stackoverflow.com/a/61486331/8227346

在 mysql 中 您可以对 ROW_NUMBER 使用分区

CREATE TABLE x As select T1.*, T2.Donations 
From xxx t1 
LEFT JOIN
 
(

  SELECT * FROM 
    (
       SELECT
          *,
          ROW_NUMBER() OVER (PARTITION BY id ORDER BY donated_amount DESC) rank
       FROM
        yy
    )
  
  WHERE
    rank = 1
)

t2
 ON (t1.id = t2.id);


可以找到更多信息https://www.c-sharpcorner.com/blogs/rownumber-function-with-partition-by-clause-in-sql-server1

答案 1 :(得分:0)

您可以使用一个子选择,它只选择给定 ID 的最高捐赠,或者您可以使用 SAS(我更喜欢)做一些前期工作:

*Order ascending by ID and DONATIONS;
proc sort data=work.t2;
  by ID DONATIONS;
run;

*only retain the dataset with the highest DONATION per ID;
data work.HIGHEST_DONATIONS;
  set work.t2;
  by ID;

  if last.ID then output;
run;

我现在没有可用的 SAS,但它应该可以工作。 不要犹豫,提出进一步的问题。 :)

相关问题