Merge

如何合併單個表中的重複行?

  • February 29, 2016

我有一張帶有重複條碼 ( barcode) 和購物車 ( cart) 和 ( Quantity_counted_IN) 和 ( Quantity_Counted_out) 的表格。

我想合併所有具有相同條碼和購物車號碼的重複記錄,以僅顯示該購物車號碼的一個條碼,但sum(Quantity_counted_IN)同時顯示sum(Quantity_Counted_out)

例子:

          cart   barcode         Quantity_Counted_In  Quantity_Counted_Out
Row 1        1   610708542209                     -7                    20
Row 2        1   610708542209                     -4                    16
Row 3        2   610708542209                     -3                    17

我希望它閱讀:

Row 1        1   610708542209                    -11                    36 
Row 2        2   610708542209                     -3                    17

我怎樣才能做到這一點?

這就是所謂的聚合查詢,

SELECT cart, barcode,
      SUM(counted_in) AS counted_in,
      SUM(counted_out) AS counted_out
FROM tbl
GROUP BY cart, barcode;

像這樣使用GROUP BY會為(購物車,條碼)的每個唯一出現返回一個記錄,以及每個記錄的 counted_in 和 counted_out 總數。

除非我可能錯過任何東西(未測試)//僅適用於 SqlServer >=2005

像這樣的東西

with CTE as
(
select barcode, sum(counted_in) as counted_in,sum(counted_out) as counted_out
from tbl
group by barcode
)
select (select top 1 cart from tbl where barcode=cte.barcode) as cart, 
barcode,counted_in,counted_out
from cte;

引用自:https://dba.stackexchange.com/questions/130727