請嘗試以下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