与SUM(Distinct)和MAX

时间:2015-12-10 23:48:16

标签: sql sql-server sql-server-2008

我有2个表:PART PCUST_ORDER_LINE COL。代码运行每个部分,直到我把它放在一起。然后我得到了可怕的:

  

“Msg 8120,Level 16,State 1,Line 2 Column   “CUST_ORDER_LINE.LAST_SHIPPED_DATE”在选择列表中无效   因为它不包含在聚合函数或   GROUP BY子句。“

PART P

|ID | QTY_ON_HAND   | QTY_ON_ORDER |
  1            20               10
  1             5                0
  2             0                0
  3            10               20
  3            15                5

CUST_ORDER LINE COL

| PART_ID   | LAST_SHIPPED_DATE
        1     1/1/2010
        1     12/1/2013
        1     12/15/2014
        2     1/1/2015
        2     3/1/2015
        3     1/1/2013

需要输出:

| ID    | Max_Date  | On_Hand   | On_Order
  1       12/25/2014       25           10              
  3       1/1/2013         25           25  

QUERY

Select P.ID,
  COL.LAST_SHIPPED_DATE As Max_Date
  Sum(Distinct P.QTY_ON_HAND) As On_Hand,
  Sum(Distinct P.QTY_ON_ORDER) As On_Order
From PART P
  Inner Join CUST_ORDER_LINE COL 
   On P.ID = COL.PART_ID
  Inner Join 
   (Select CUST_ORDER_LINE.PART_ID,MAX(CUST_ORDER_LINE.LAST_SHIPPED_DATE) As Max_Date
   From CUST_ORDER_LINE  
   Group By PART_ID)col2
   On [ COL2].PART_ID = COL.PART_ID
    and col2.max_date = col.LAST_SHIPPED_DATE
Group By P.ID
Having Sum(Distinct P.QTY_ON_HAND) != 0
Order By P.ID

2 个答案:

答案 0 :(得分:0)

您可以在group by子句中包含COL.LAST_SHIPPED_DATE,也可以在聚合函数中包含该列:

Select P.ID,
  max(COL.LAST_SHIPPED_DATE) As Max_Date

如果你有group by子句......任何不在子句中的字段必须只在选择输出中的某个聚合函数内部使用。

答案 1 :(得分:0)

尝试以下查询

select PART_ID, On_Hand,On_Order,max(LAST_SHIPPED_DATE) Max_Date
         from CUST_ORDER_LINE a inner join(
        select id,sum(QTY_ON_HAND) On_Hand ,sum(QTY_ON_ORDER) On_Order
         from PART group by id having sum(QTY_ON_HAND)!=0) t on a.PART_ID=t.ID
        group by PART_ID,On_Hand,On_Order