使用group by进行SELECT查询

时间:2016-10-19 14:07:40

标签: sql sql-server group-by

我不知道为什么以下查询无效:

SELECT whs_code, pdt_code,case_dt_yyyymmdd, fresh_frozen_status, 
SUM(qty_cases_on_hand)-Qty, SUM(qty_weight_on_hand)-Wt, operation
    FROM 
    (
        SELECT whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation,SUM(qty_cases_on_hand) AS Qty, SUM(qty_weight_on_hand) AS Wt
            FROM tbl_inventory_activity_rpt1 
                WHERE operation ='RU'
                GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation 
    ) 
    WHERE operation='SU'
    GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation`

错误是:

  

Msg 156,Level 15,State 1,Line 4关键字' WHERE'附近的语法不正确。


为了便于理解我在这里尝试做什么,请参见示例
我需要数据作为

的结果
(SELECT x FROM tbl_table Where column y='SU')-(SELECT x FROM tbl_table Where column y='RU')

1 个答案:

答案 0 :(得分:1)

    SELECT ru.whs_code,
           ru.pdt_code,
           ru.case_dt_yyyymmdd,
           ru.fresh_frozen_status,
           ru.operation,
           ru.Qty - su.Qty AS Qty_Diff,
           ru.Wt - su.Wt AS Wt_Diff
      FROM    
    (
        SELECT whs_code,
               pdt_code,
               case_dt_yyyymmdd,
               fresh_frozen_status,
               operation,
               SUM(qty_cases_on_hand) AS Qty, 
               SUM(qty_weight_on_hand) AS Wt
          FROM tbl_inventory_activity_rpt1 
         WHERE operation ='RU'
       GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation 
    ) ru,
    (
        SELECT whs_code,
               pdt_code,
               case_dt_yyyymmdd,
               fresh_frozen_status,
               operation,
               SUM(qty_cases_on_hand) AS Qty, 
               SUM(qty_weight_on_hand) AS Wt
          FROM tbl_inventory_activity_rpt1 
         WHERE operation ='SU'
       GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation 
    ) su
WHERE ru.whs_code = su.whs_code
  AND ru.pdt_code = su.pdt_code
  AND ru.case_dt_yyyymmdd = su.case_dt_yyyymmdd
  AND ru.fresh_frozen_status = su.fresh_frozen_status
  AND ru.operation = su.operation;