日期:2014-05-18  浏览次数:20590 次

常见SQL问题,急请大大们帮忙!
各位新年好!请帮忙看看:
有视图V,含如下记录(为清晰起见,故分为5组):
SQL code

Aid   Aname   AE     AR
1    AN1    ae1    ar10
1    AN1    ae1    ar12
1    AN1    ae1    ar13
1    AN1    ae1    ar14

2    AN2    ae2    ar20
2    AN2    ae2    ar21
2    AN2    ae2    ar22
2    AN2    ae2    NULL

2    AN2    ae3    NULL
2    AN2    ae3    NULL
2    AN2    ae3    ar23
2    AN2    ae3    ar24

2    AN2    ae4    ar25
2    AN2    ae4    ar26
2    AN2    ae4    NULL
2    AN2    ae4    ar27

2    AN2    ae5    NULL
2    AN2    ae5    NULL
2    AN2    ae5    NULL
2    AN2    ae5    NULL


想要查询结果(需要写的SQL:只返回不同Aid的第一行数据即可,具体要求请见下面说明):
SQL code

Aid   Aname   AE    AR
1    AN1    ae1    ar10
2    AN2    ae2    ar20


说明:视图V是已经创建的中间数据,AE和AR字段(在实际中均对应多列,现把它们各抽象为一组列),一个AE对应4个AR, 同一个Aid最多有4个AE (最少1个),则AR最多有(4x4)16个(最少4个) ,实际业务中动态查询的情况:
1. 当AE的个数等于1时,则对应的(4个) 任意一个AR值都有可能为空.(为空的用0代替);
2. 当AE的个数大于1时,则对应的每组中的任意一个AR值都有可能为空.(为空的用0代替)


备注: 1.每组AE之间应该用AND连接吧(因为对应的实际业务数据都为同一个Aid的属性)
  2. AE与本组的AR之间也应该用AND连接吧( 原因同上)
  3. AE和AR是在程序中要输入查询的参数(即可输入4个AE值,16个AR值进行查询).








------解决方案--------------------
探讨

SQL code

select * from [tb] t where not exists(select 1 from [tb] where [Aid]=t.[Aid]and [AR]<t.[AR])
and[AR] is not null
----------------结果----------------------------
/*
Aid Aname AE AR……

------解决方案--------------------
探讨

谢谢大家的回复: 回1楼:不只是返回结果哦,您的SQL无法去和实际的字段去匹配查询哦;
回4楼:可以Aid为排序,且在实际中每组AE中的每个AR值都允许相同,不同AE组的AR值也允许相同(虽然极少出现这种情况),这点很重要哦!(不是以AR或AE为排序的)

------解决方案--------------------
select t.* from tb t where ar is not null and not exists (select 1 from tb where ar is not null and aid = t.aid and aname = t.aname and (ae < t.ae or (ae = t.ar and ar < t.ar)))