日期:2014-05-17  浏览次数:20720 次

急~~~~~查询各公司的一条记录
举列子表:id,com_id,product_id
  1,1001,2001
  2,1001,2002
  3,1001,2003
  4,1002,2004,
  5,1002,2005
  6,1003,2008
需要把各公司都取出来,并且只取一条产品信息的,结果比如:
  1,1001,2001
  5,1002,2005
  6,1003,2008
要求是sql语句搞定,不要存储过程,游标啥的,
谢谢各位大侠,重分答谢,急~~~~

------解决方案--------------------
select min(id),com_id,min(product_id) from table group by com_id order by com_id
------解决方案--------------------
可以直接分组取最小值 也可以使用row_number() over()取第一列
------解决方案--------------------
不晓得你是要返回每组的最小?最大?
这是随机返回每组的一条记录
SQL code
WITH t AS (
SELECT 1 id,1001 com_id,2001 product_id FROM dual
UNION ALL 
SELECT 2,1001,2002 FROM dual
UNION ALL 
SELECT 3,1001,2003 FROM dual
UNION ALL 
SELECT 4,1002,2004 FROM dual
UNION ALL 
SELECT 5,1002,2005 FROM dual
UNION ALL 
SELECT 6,1003,2008 FROM dual
)
SELECT id,com_id,product_id FROM 
(
  SELECT t.*,Row_Number() over (PARTITION BY com_id ORDER BY dbms_random.random)rn FROM t
)
WHERE rn=1 
ORDER BY com_id;

------解决方案--------------------
由于楼主也没有说取值的大小规则,所以推测奇数ID的公司取时间最大值,偶数ID的公司取时间最小值,故代码为:

SQL code
with t as 
(select 1001 id,2001 year from dual
union all
select 1001 ,2002 from dual
union all
select 1001 ,2003 from dual
union all
select 1002 ,2004 from dual
union all
select 1002 ,2005 from dual
union all
select 1003 ,2008 from dual)
select id,case when mod(id, 2) = 0 then max(year) else min(year) end
  from t
 group by id
 order by id;