数据库查询问题???高手指教!!!!
id uersId userName content datetime
1 34 dd sfsfsd 2000-5-6
2 43 aa sfsfsd 2001-2-6
3 34 dd sfsfsd 2005-5-6
4 34 dd sfsfsd 2000-5-6
5 43 aa sfsfsd 2007-9-14
6 43 aa sfsfsd 2002-8-6
如表:我想查出按时间排序,uersId中34,43中的前两条记录.怎么做啊?
------解决方案--------------------userid等于34和43范围内的:
select top 2 [id],userid,content,[datetime] from 表名
where userid in( '34 ', '43 ') order by [datetime]
------解决方案--------------------是这个意思吗?
Select Top 2 * From TableName Where UserID In (34, 43) Order By datetime
------解决方案-------------------- select top 2 * from 表 where uersId in (select distinct uersId from 表) order by datetime
子查询就可搞定了! 简单
------解决方案--------------------select top 2 * from 表名
where userid in( '34 ', '43 ') order by [datetime]
------解决方案--------------------方法多多,
select top 2 * from Table where userid=34 or userid=43 order by datetime desc
------解决方案--------------------select top 2 * from 表 where userid in(select DISTINCT userid from 表)order by[datetime]
------解决方案--------------------應該是取每組的前兩位吧,
try
--方法一:
Select * From TableName A
Where (Select Count(*) From TableName Where uersId = A.uersId And [datetime] > A.[datetime]) < 2
Order By uersId, [datetime]
--方法二:
Select * From TableName A
Where Exists (Select Count(*) From TableName Where uersId = A.uersId And [datetime] > A.[datetime] Having Count(*) < 2)
Order By uersId, [datetime]
--方法三:
Select * From TableName A
Where [datetime] In (Select TOP 2 [datetime] From TableName Where uersId = A.uersId Order By [datetime] Desc)
Order By uersId, [datetime]
------解决方案--------------------试试这个,希望没理解错,
SELECT * FROM test
WHERE [datetime] IN (SELECT MAX([datetime]) FROM test GROUP BY userId)