使用group by和order by按升序排列数据的问题

时间:2015-11-09 15:47:11

标签: sql database

我正在尝试按照货件编号和物品编号按升序获得装运日期,但无法使用以下查询来执行此操作

Select s.shipment_date, s.shipment_number,i.item_number
  from Shipment_Item si
  Inner Join Shipment s on s.shipment_id = si.shipment_id
  Inner Join Item_master i on i.item_id = si.item_id
  where s.shipment_date between '1/1/14' and '12/31/14'
  group by i.item_number, s.shipment_number, s.shipment_date 

如果我使用此查询

  Select s.shipment_date, s.shipment_number,i.item_number
  from Shipment_Item si
  Inner Join Shipment s on s.shipment_id = si.shipment_id
  Inner Join Item_master i on i.item_id = si.item_id
  where s.shipment_date between '1/1/14' and '12/31/14'
  group by i.item_number, s.shipment_number
  order by s.shipment_date

我得到以下内容 列'Shipment.Shipment_Date'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

2 个答案:

答案 0 :(得分:1)

group by子句中的字段不指定输出的顺序。它仅指定分组。如果您希望对它们进行分组和排序,则必须将列放在以下两个子句中:

Select s.shipment_date, s.shipment_number,i.item_number
  from Shipment_Item si
  Inner Join Shipment s on s.shipment_id = si.shipment_id
  Inner Join Item_master i on i.item_id = si.item_id
  where s.shipment_date between '1/1/14' and '12/31/14'
  group by i.item_number, s.shipment_number, s.shipment_date 
  order by i.item_number, s.shipment_number, s.shipment_date 

答案 1 :(得分:0)

分组条款应该是:group by i.item_number,s.shipment_number,s.shipment_date