SQL Group by Not working。

时间:2015-01-07 17:56:29

标签: mysql sql view group-by

我从一个视图中提取了很长的SQL项目列表,我需要做的是分组,但只有两个项目 -

例如:

select distinct 
a.customer_no   ,
a.customer_prefix   ,
a.customer_lname    ,
a.customer_street1
... -- about 100 other rows 
a.inv_mail_dt,
a.pmt_due_dt,
a.pmt_rcvd_dt,
a.pmt_rcvd_amt,
a.perf_date,
a.perf_desc,
a.sub_line_item_price_type_desc ,
a.Price_type_desc,
sum(a.sli_due_amt),
sum(a.sli_paid_amt)
from VIEW a
Where a.customer_no = @customer_no
Group by 
a.customer_no,
a.order_no,
a.Price_type_desc

但我不断收到错误消息,要求我将其他列/字段添加到该组中。但那些不应该被用来分组,如果它们是唯一的那么它们应该是分开的,如果它们是相同的

1 个答案:

答案 0 :(得分:2)

  

但是如果它们是唯一的那些[列]不应该被用来分组,那么如果它们是相同的那么它们应该是分开的

那不是GROUP BY的工作方式。您在select中指定的每个表达式必须是以下两种类型之一:

  • GROUP BY - 即GROUP BY列表中的列,或
  • 汇总表达式 - 即选择MINMAXSUMCOUNT等的函数

GROUP BY查询将使用" group by"用于将结果拆分为" buckets"的列,在每个桶中执行聚合,并将结果返回给您。

由于在GROUP BY列表中添加更多列可能会导致创建比您需要的更多的存储桶,解决此问题的另一种方法是完全删除未使用的列,运行GROUP BY和&# 34;平坦"单独查询,并在RDBMS或主机环境中加入结果:

select distinct 
    a.customer_no,
    a.order_no,
    a.Price_type_desc,
    a.customer_prefix,
    a.customer_lname,
    a.customer_street1
    ... -- about 100 other rows 
    a.inv_mail_dt,
    a.pmt_due_dt,
    a.pmt_rcvd_dt,
    a.pmt_rcvd_amt,
    a.perf_date,
    a.perf_desc,
    a.sub_line_item_price_type_desc,
    x.sum_sli_due_amt,
    x.sum_sli_paid_amt
from VIEW a
join (
    SELECT
    b.customer_no,
    b.order_no,
    b.Price_type_desc,
    sum(b.sli_due_amt) as sum_sli_due_amt,
    sum(b.sli_paid_amt) as sum_sli_paid_amt
    from VIEW b
    Group by 
    b.customer_no,
    b.order_no,
    b.Price_type_desc
   Where b.customer_no = @customer_no
) x ON a.customer_no=x.customer_no
   AND a.order_no=x.order_no
   AND a.Price_type_desc=x.Price_type_desc
Where a.customer_no = @customer_no