我遇到一些SQL的问题,我无法解决问题。
现在我运行的查询主要是:
SELECT Q.ID, Q.STATUS, C.LASTNAME, C.FIRSTNAME,
C.POSTAL, C.PHONE
FROM QUEUE Q
LEFT OUTER JOIN CUSTOMER C ON Q.ID = C.APPID
WHERE C.LASTNAME LIKE 'SMITH%'
此查询中有大约200条记录。我的问题是同一个人有多次出现。
Q.ID Q.STATUS C.LASTNAME C.FIRSTNAME ETC...
1 A SMITH JOHN
2 A SMITH RYAN
3 B SMITH BRIAN
100 A SMITH RYAN
200 A SMITH RYAN
我需要返回的是
Q.ID Q.STATUS C.LASTNAME C.FIRSTNAME ETC...
1 A SMITH JOHN
3 B SMITH BRIAN
200 A SMITH RYAN
请有人指出我正确的方向。我试过了
SELECT WHATEVER FROM TABLE WHERE Q.ID IN (SELECT MAX(ID) FROM TABLE WHERE BLAH BLAH)
专门搜索“RYAN SMITH”时有效。但我需要显示具有最高ID的SMITH的所有结果。
感谢任何帮助。
干杯
答案 0 :(得分:1)
我猜你可以做类似下面的事情
SELECT WHATEVER FROM TABLE
WHERE Q.ID IN
(SELECT MAX(ID) FROM TABLE
WHERE BLAH...BLAH
GROUP BY C.FIRSTNAME, C.LASTNAME)
希望这会有所帮助!!
答案 1 :(得分:0)
select * from Table where id in (
select max(q.id) from Table group by c.lastname, c,firstname
)
答案 2 :(得分:0)
假设有一个CUSTOMER.ID
,我认为我是对的,这就是:
SELECT Q.ID, Q.STATUS, M.LASTNAME, M.FIRSTNAME,
M.POSTAL, M.PHONE
FROM QUEUE Q
LEFT OUTER JOIN (
SELECT C2.ID CID,
MAX(C2.FIRSTNAME) FIRSTNAME,
MAX(C2.LASTNAME) LASTNAME,
MAX(C2.POSTAL) POSTAL,
MAX(C2.PHONE) PHONE,
MAX(Q2.ID) QID
FROM QUEUE Q2
LEFT OUTER JOIN CUSTOMER C2 ON Q2.ID = C.APPID
WHERE C2.LASTNAME LIKE 'SMITH%'
GROUP BY C2.ID
) M ON (M.QID = Q.ID)
答案 3 :(得分:0)
如果我理解得很好,这应该有效:
SELECT Q.ID
, Q.STATUS
, C.LASTNAME
, C.FIRSTNAME,
, C.POSTAL
, C.PHONE
FROM QUEUE Q
join CUSTOMER C ON Q.ID = C.APPID
WHERE C.LASTNAME like 'SMITH%'
and not exists (SELECT *
FROM CUSTOMER innerCustomer
WHERE innerCustomer.LASTNAME like 'SMITH%'
and innerCustomer.APPID > C.APPID
)
注意:我已经通过“内部联接”更改了“左连接”,因为您要根据C.LASTNAME进行过滤。所以我认为左连接没有多少意义。