sql分区通过抑制重复值

时间:2009-06-08 18:57:32

标签: sql

使用SQL Server(2005/2008)

是否有一种简单的方法来抑制重复的子&总计?

select h.salesmanno ,c.custname ,h.amt ,sum(h.amt) over (partition by salesmanno) as subtotal
,sum(h.amt) over (partition by null) as grandtotal
from hdr h, cust c WHERE h.custno = c.custno and h.hdate = '6/8/2009'

在组更改

之前,除了最后一个位置外,基本上抑制(或为空)

谢谢!

2 个答案:

答案 0 :(得分:1)

这是什么数据库?在SQL Server上,类似这样的事情可以:

select
  salesmanno, custname, amt
, case when subtotal_no = subtotal_count then subtotal end as subtotal
, case when total_no = total_count then subtotal end as total
from (
  select 
    h.salesmanno 
  , c.custname 
  , h.amt 
  , sum(h.amt) over (partition by salesmanno) as subtotal
  , sum(h.amt) over (partition by null) as grandtotal
  , row_number() over (partition by salesmanno order by custname) as subtotal_no
  , row_number() over (partition by null order by salesmanno, custname) as as total_no
  , count(*) over (parition by salesmanno) as subtotal_count
  , count(*) over (parition by null) as total_count
  from hdr h, cust c 
  WHERE h.custno = c.custno 
    and h.hdate = '6/8/2009'
  ) a
order by total_no

更短的版本,更多的数据库排序,可能不太明显正在发生的事情:

select
  salesmanno, custname, amt
, case when subtotal_no = 1 then subtotal end as subtotal
, case when total_no = 1 then subtotal end as total
from (
  select 
    h.salesmanno 
  , c.custname 
  , h.amt 
  , sum(h.amt) over (partition by salesmanno) as subtotal
  , sum(h.amt) over (partition by null) as grandtotal
  , row_number() over (partition by salesmanno order by custname desc) as subtotal_no
  , row_number() over (partition by null order by salesmanno desc, custname desc) as as total_no
  from hdr h, cust c 
  WHERE h.custno = c.custno 
    and h.hdate = '6/8/2009'
  ) a
order by total_no desc

或者,使用ROLLUP生成小计和总行:

  select 
    h.salesmanno 
  , c.custname 
  , sum(h.amt) as amt
  from hdr h, cust c 
  WHERE h.custno = c.custno 
    and h.hdate = '6/8/2009'
  group by 
    h.salesmanno 
  , c.custname 
  with rollup 
  order by
    h.salesmanno 
  , c.custname 

要以正确的顺序获得结果,请将顺序更改为以下内容:

  order by
    grouping(h.salesmanno)
  , h.salesmanno
  , grouping(c.custname)
  , c.custname 

答案 1 :(得分:0)

将其嵌套在子查询中,并在WHERE

中添加过滤器
SELECT *
FROM (
select h.salesmanno ,c.custname ,h.amt ,sum(h.amt) over (partition by salesmanno) as subtotal
,sum(h.amt) over (partition by null) as grandtotal
from hdr h, cust c WHERE h.custno = c.custno and h.hdate = '6/8/2009' 
) AS X
WHERE whatever