日期:2014-05-17 浏览次数:20592 次
--查询临时表B,按GID,UserID分类,取记录的最大的ID
select max(ID) from #B group by GID,UserID
--如果想查表B所有信息,那么就这样
select * from #B
where ID in(
select max(ID) from #B group by GID,UserID
)
--如果想联合查询表A,表B,Join on就可以了,这个不用写了吧
CREATE TABLE A(
id int,
GID nvarchar(20),
thisName nvarchar(20)
)
CREATE TABLE b(
id int,
GID nvarchar(20),
UserID int
)
INSERT INTO A(id,GID,thisName)
SELECT 1,'A1','张三' UNION ALL
SELECT 2,'A2','李四'
INSERT INTO b(id,GID,UserID)
SELECT 1,'A1',2 UNION ALL
SELECT 2,'A1',2 UNION ALL
SELECT 3,'A2',3 UNION ALL
SELECT 4,'A2',3 UNION ALL
SELECT 5,'A2',3 UNION ALL
SELECT 6,'A2',1
SELECT a.*,b.* FROM a inner join (SELECT max(GID) as GID FROM b group by userID) b on a.GID=b.GID