我的表有几条记录,它们具有相同的MemberID。我想只得到一条记录。
select DISTINCT(MemberID) from AnnualFees;
然后结果会来。但我想显示其他列数据,但是当我这样做时
select DISTINCT(MemberID),StartingDate,ExpiryDate,Amount from AnnualFees;
还显示包含相同MemberID数据的所有详细信息。
有人可以帮助我。答案 0 :(得分:20)
假设你只想为每个memberid随机选择任何一行,你可以这样做:
select memberid, this, that, theother
from
(
select memberid, this, that, theother,
row_number() over (partition by memberid order by this) rn
from annualfees
)
where rn = 1;
如果您希望每个memberid有一个特定的行,例如使用最新StartDate的那个,然后您可以将其修改为:
select memberid, this, that, theother
from
(
select memberid, this, that, theother,
row_number() over (partition by memberid order by StartDate desc) rn
from annualfees
)
where rn = 1;
答案 1 :(得分:6)
不知道这是否是您需要的,但您可能需要查看GROUP BY而不是DISTINCT ......
如果您有多个具有相同成员ID的记录,则可能需要指定exaclty如何从其他记录中识别出您想要的记录
例如,要了解每个成员的最后开始日期:
SELECT memberid, max(startingdate)
FROM annualfees
GROUP BY memberid
但如果您需要以这种方式识别一条记录,但也显示其他列,我认为you may need to do some trickery like this ......
例如使用连接子查询上述SELECT以加入您想要的其他列:
SELECT subq.memid, subq.startdate, a.expirydate, a.amount
FROM (
SELECT memberid AS memid, max(startingdate) AS startdate
FROM annualfees
GROUP BY memberid ) subq
INNER JOIN annualfees a ON a.memberid = subq.memid
AND a.startingdate = subq.startdate
从头到尾,还显示数据表(使用“SET VERIFY ON”跟踪/抓取o / p)...
-- show all rows
select *
from annualfees
order by memberid, startingdate
MEMBERID STARTINGDATE EXPIRYDATE AMOUNT
---------------------- ------------------------- -------------------- --------------------
1 02-DEC-09 05-FEB-10 111
1 25-JUN-10 25-JUN-11 222
2 25-APR-10 25-JUN-13 333
3 rows selected
/
-- show one member`s data using max(startingdate) as selector.
SELECT memberid, max(startingdate)
FROM annualfees
GROUP BY memberid
MEMBERID MAX(STARTINGDATE)
---------------------- -------------------------
1 25-JUN-10
2 25-APR-10
2 rows selected
/
-- show above data joined with the other columns.
SELECT subq.memid, subq.startdate, a.expirydate, a.amount
FROM (
SELECT memberid AS memid, max(startingdate) AS startdate
FROM annualfees
GROUP BY memberid ) subq
INNER JOIN annualfees a ON a.memberid = subq.memid AND a.startingdate = subq.startdate
MEMID STARTDATE EXPIRYDATE AMOUNT
---------------------- ------------------------- -------------------- --------------------
1 25-JUN-10 25-JUN-11 222
2 25-APR-10 25-JUN-13 333
2 rows selected
/
答案 2 :(得分:3)
您需要选择具有重复MemberID的哪些行以某种方式返回。这将获得具有最大startingDate的行。
SELECT MemberID,StartingDate,ExpiryDate,Amount
FROM AnnualFees af
WHERE NOT EXISTS (
SELECT * from AnnualFees af2
WHERE af2.MemberID = af.MemberID
AND af2.StartingDate > af.StartingDate)
答案 3 :(得分:-3)
选择DISTINCT会员ID,开始日期,到期日,年度金额;
删除paranthesis