选择SAS SQL中的第一个匹配项

选择SAS SQL中的第一个匹配项,sql,sql-server,sas,Sql,Sql Server,Sas,我试图在两种情况下选择记录的第一次出现,但都没有成功。这是我的密码: PROC SQL; CREATE TABLE table1 AS SELECT user_id, type, date, money FROM table2 WHERE date IN (SELECT MIN(date) FROM twice_transaction GROUP BY user_id,type); 例如,原始表如下所示(表2) 但我只想:(表1) 我应该如何修改/编码以获得最终结果?谢谢 使用SQL有几

我试图在两种情况下选择记录的第一次出现,但都没有成功。这是我的密码:

PROC SQL;

CREATE TABLE table1 AS
SELECT user_id, type, date, money 
FROM table2
WHERE date IN (SELECT MIN(date) 
FROM twice_transaction
GROUP BY user_id,type);
例如,原始表如下所示(表2)

但我只想:(表1)


我应该如何修改/编码以获得最终结果?谢谢

使用SQL有几种方法可以做到这一点。@NoDisplayName的注释向您展示了一种更传统的SAS方法

CREATE TABLE table1 AS
SELECT a.user_id, a.type, a.date, a.money 
FROM table2 as a
INNER JOIN
SELECT (user_id, type, min(date) as date from table2 group by user_id, type) as b 
on a.user_id = b.user_id
and a.type = b.type
and a.date = b.date;

我在这里所做的是创建一个内部选择,以按用户id和类型获取最小日期。然后,我使用一个内部联接从第一个表中选择与第二个表对齐的记录。

使用HAVING子句也是一个选项

data have;
informat usert type $8. date mmddyy10. money $8.;
format date date9.;
input usert  type  date      money;
cards;
user1 type1 1/10/2012 money1
user1 type1 2/20/2012 money2
user1 type2 1/15/2012 money3
user1 type2 2/28/2012 money4
user2 type1 3/28/2012 money5
user2 type2 2/14/2012 money6
user2 type2 4/13/2012 money7
;
run;

proc sql;
create table want as
select usert, type, date, money
from have
group by usert, type
having date=min(date);
quit;

从SQL的角度来看,这是一个典型的问题。(在本例中是“最少”,但名称实际上指的是某事物的“顶部”)如果要在SAS中使用top或WINDOW函数,则需要使用显式SQL传递。这不是MySQL,不能包含不在
GROUP BY
或聚合函数中的列(即使可以,
money
也不一定包含给定最小日期行的匹配值,尽管可能性非常高).@clockwork Muse SAS允许包含不在GROUP BY中的列,并且AFAIK确实包含给定最小值的匹配值。SAS可能会这样做,但看起来您是在告诉它确切地运行特定的SQL语句,SQL Server会很高兴地抱怨这一点。它位于PROC SQL块中,没有使用显式传递到DB,因此它是SAS SQL。如果它是显式传递,那么它必须是有效的SQL。
CREATE TABLE table1 AS
SELECT a.user_id, a.type, a.date, a.money 
FROM table2 as a
INNER JOIN
SELECT (user_id, type, min(date) as date from table2 group by user_id, type) as b 
on a.user_id = b.user_id
and a.type = b.type
and a.date = b.date;
data have;
informat usert type $8. date mmddyy10. money $8.;
format date date9.;
input usert  type  date      money;
cards;
user1 type1 1/10/2012 money1
user1 type1 2/20/2012 money2
user1 type2 1/15/2012 money3
user1 type2 2/28/2012 money4
user2 type1 3/28/2012 money5
user2 type2 2/14/2012 money6
user2 type2 4/13/2012 money7
;
run;

proc sql;
create table want as
select usert, type, date, money
from have
group by usert, type
having date=min(date);
quit;