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

关于group by 的问题
[code=SQL][/code]

select obj.stock_type as stock_type,
  obj.stock_detail_id as stock_detail_id,
  obj.inv_id as inv_id,
  obj.owner_type as owner_type,
  obj.cust_id as cust_id,
  obj.stock_id as stock_id,
  obj.batch_no as batch_no,
  obj.unit as unit,
  obj.create_time as create_time,
  inv.inv_name as inv_name,
  st.stock_name as stock_name,
  sum(obj.qty)
  from MT_INV_STOCK obj
  left join BM_INVENTORY inv
  on inv.inv_id = obj.inv_id
  left join BM_STOCK st
  on st.stock_id = obj.stock_id
  where inv.inv_type_id = 231 
 group by obj.inv_id,obj.stock_type,obj.stock_detail_id,obj.owner_type ,obj.cust_id ,obj.stock_id,
  obj.batch_no,obj.unit,obj.create_time,inv.inv_name , st.stock_name
   
---group by 使用时必须列出所有在select 和order by后面出现的字段除了聚合函数外。

Q:group by 分组是按顺序分组的?分组时必须group by后面每列的值相同才能是一组?如果我只想要按一组分怎么做?


------解决方案--------------------
实测数据:
SQL code

CREATE TABLE T160
(
    ID NUMBER(4),
    NAME VARCHAR2(20),
    Age NUMBER(2),
    Amount NUMBER(4)
);
INSERT INTO T160 VALUES(1, 'A', 10, 100);
INSERT INTO T160 VALUES(2, 'B', 10, 200);
INSERT INTO T160 VALUES(3, 'C', 20, 300);
INSERT INTO T160 VALUES(4, 'D', 30, 400);
INSERT INTO T160 VALUES(5, 'E', 30, 500);
INSERT INTO T160 VALUES(6, 'F', 40, 600);