表A(id,test,cid)
表B(id,test,aid)
已知cid in (10000,10001,10002)
如何根据A表cid得到的id去操作B表,分别得到B表关于aid top 3 order by id desc的内容
但是一定要保证每一个cid操作下的B表都有3个记录
可以参考 点击进入这个页面
有点绕口,我自己都不知道该如何表达
还有,最后得到的结果,我希望可以根据cid来
DataView dv = tb.DefaultView;
dv.RowFilter = "cid= " + cidInne;
这样子
------解决方案--------------------
cid--A/B此列都是字符串(10000,10001,10002)?
------解决方案--------------------
比较保险的方法,
- SQL code
(select top 3 *from 表A ainner join 表B b on a.id=b.aidwhere a.cid in (10000)order by b.id desc)union all(select top 3 *from 表A ainner join 表B b on a.id=b.aidwhere a.cid in (10001)order by b.id desc)union all(select top 3 *from 表A ainner join 表B b on a.id=b.aidwhere a.cid in (10002)order by b.id desc)
------解决方案--------------------
- SQL code
--得到每组前几条数据--假設每組Col1中, Col3不會重復--建立測試環境Create Table TEST(Col1 Varchar(10), Col2 Varchar(10), Col3 Int)--插入數據Insert TEST Select 'BD1V','Label', 4Union All Select 'BD1V', 'BATT', 2Union All Select 'BD1V', 'ODD', 3Union All Select 'BD1V', 'HDD', 5Union All Select 'BD1V', 'LCD', 1Union All Select 'BD1W','HDD', 3Union All Select 'BD1W','RAM', 8Union All Select 'BD1W','TP CABLE', 5Union All Select 'BD1W','LCD', 6Union All Select 'BD1W','Label', 2Union All Select 'BL3', 'LCD CABLE', 7Union All Select 'BL3', 'LABEL', 6Union All Select 'BL3', 'LCD', 5Union All Select 'BL3', 'RAM', 1Union All Select 'BL3D', 'Label', 4GO--測試--方法一:Select Col1, Col2, Col3 From TEST AWhere (Select Count(*) From TEST Where Col1 = A.Col1 And Col3 > A.Col3) < 3Order By Col1, Col3 Desc--方法二:Select Col1, Col2, Col3 From TEST AWhere Exists (Select Count(*) From TEST Where Col1 = A.Col1 And Col3 > A.Col3 Having Count(*) < 3)Order By Col1, Col3 Desc--方法三:Select Col1, Col2, Col3 From TEST AWhere Col3 In (Select TOP 3 Col3 From TEST Where Col1 = A.Col1 Order By Col3 Desc)Order By Col1, Col3 DescGO--刪除測試環境Drop Table TEST--結果/*Col1 Col2 Col3BD1V HDD 5BD1V Label 4BD1V ODD 3BD1W RAM 8BD1W LCD 6BD1W TP CABLE 5BL3 LCD CABLE 7BL3 LABEL 6BL3 LCD 5BL3D Label 4*/
------解决方案--------------------
- SQL code
--如果是查询:select a.* , t.* from a , b twhere a.id = t.aid and t.id in (select top 3 id from b where aid = t.aid order by id)select a.* , t.* from a , b twhere a.id = t.aid and t.id in (select top 3 id from b where aid = t.aid order by id desc)