请尝试以下sql
假设@tempData是您的表名称。
declare @tempData table
(
supplier nvarchar(20),
reference nvarchar (20),
xDescription nvarchar(20),
total int
);
insert into @tempData
select 'smiths', 'BP657869510L' ,NULL, 42 union all
select 'smiths', 'BP657869510L' ,NULL, 42 union all
select 'smiths', 'BP654669510L' ,'No. 5621', 13 union all
select 'smiths', 'BP654669510L' ,'No. 5621', 13 union all
select 'corrigan', '15:51' ,'Order 23542', 23 union all
select 'corrigan', '15:51' ,'Order 23542', 23 union all
select 'williams', '14015' ,'Block B', 19 union all
select 'williams', '14015' ,'Block B', 19
;
select
a.supplier
, a.reference
, a.xDescription
, a.total
from @tempData a
group by a.supplier
, a.reference
, a.xDescription
, a.total
;
/*
supplier reference xDescription total
-------------------- -------------------- -------------------- -----------
corrigan 15:51 Order 23542 23
smiths BP654669510L No. 5621 13
smiths BP657869510L NULL 42
williams 14015 Block B 19
*/
with cte as
(
select
a.supplier
, a.reference
, a.xDescription
, a.total
from @tempData a
group by a.supplier
, a.reference
, a.xDescription
, a.total
)
select
distinct c.supplier, sum(c.total) over(partition by c.supplier) as total
from cte c
;
/*
supplier total
-------------------- -----------
corrigan 23
smiths 55
williams 19
*/
UPDATE
的请求,该查询的目的是包括具有不同的描述中,相同的供应商独立的记录:例如供应商史密斯
DENSE_RANK()将满足该请求(http://technet.microsoft.com/en-us/library/ms173825(v=sql.90).aspx)
with cte as
(
select
a.supplier
, a.reference
, a.xDescription
, a.total
,dense_rank() over(partition by a.supplier order by a.supplier, a.xDescription) as dRow
from @tempData a
group by a.supplier
, a.reference
, a.xDescription
, a.total
)
select
distinct c.supplier, sum(c.total) over(partition by c.supplier,drow) as total
from cte c
;
/*
supplier total
-------------------- -----------
corrigan 23
smiths 13
smiths 42
williams 19
*/
查看全部现场
with cte as
(
select
a.supplier
, a.reference
, a.xDescription
, a.total
,dense_rank() over(partition by a.supplier order by a.supplier, a.xDescription) as dRow
from @tempData a
group by a.supplier
, a.reference
, a.xDescription
, a.total
)
select
distinct c.supplier, c.reference,c.xDescription, sum(c.total) over(partition by c.supplier,drow) as total
from cte c
;
是有可能 – cyan
你的解释是混乱。每个'供应商'有可能有不同的参考?如果有不同的'Reference'与'Total'相同,你还想只考虑一行吗?如果“描述”不同,可以随机选择哪一个? – dnoeth
是的,每个'供应商'都可以有不同的'参考' - 我通过在不同'参考'条目下的样品表中为'供应商''史密斯'分配条目来证明这一点。我希望每一行都有一个唯一的'Reference'来考虑数量是否相同。如果'Reference'中的'Description'不同,那么'Reference'是相同的行,我没有偏好选择哪一个,但理想情况下我想返回其中的一个。 – James