在SQL Server视图中加入和求和值

时间:2015-09-14 15:12:35

标签: sql sql-server

我正在尝试实现此目的:我在SQL Server 2012中有一个视图,结果集如下:

id sku  quantity  fieldtax  tax2
--------------------------------
1  2607   1        10         7
2  2607   2        10         7
3  55612  5         7        15

我想让结果集看起来像这样:

id sku  quantity  fieldtax  tax2
---------------------------------
1  2607   3        10        7
3  55612  5         7       15

我需要对具有相同sku的列求和 - 我该如何实现?

我已经尝试过这是完整的表格:

SELECT
    VENTAS_AGRUPADAS.id,
    VENTAS_AGRUPADAS.TransactionType,
    VENTAS_AGRUPADAS.TransactionModifier,
    VENTAS_AGRUPADAS.SKU,
    VENTAS_AGRUPADAS.Tax1,
    VENTAS_AGRUPADAS.Tax2,
    SUM(VENTAS_AGRUPADAS.Quantity) AS QUANTITY,
    VENTAS_AGRUPADAS.Tax3,
    VENTAS_AGRUPADAS.TransactionNumber
FROM 
    dbo.VENTAS_AGRUPADAS
GROUP BY 
    VENTAS_AGRUPADAS.id,
    VENTAS_AGRUPADAS.TransactionType,
    VENTAS_AGRUPADAS.TransactionModifier,
    VENTAS_AGRUPADAS.SKU,
    VENTAS_AGRUPADAS.Tax1,
    VENTAS_AGRUPADAS.Tax2,
    VENTAS_AGRUPADAS.Tax3,
    VENTAS_AGRUPADAS.TransactionNumber
ORDER BY 
    VENTAS_AGRUPADAS.SKU DESC

谢谢

2 个答案:

答案 0 :(得分:4)

Perhaps this, if fieldtax and tax2 always will be the same for an sku:

select sku, SUM(quantity), fieldtax, tax2
from tablename
group by sku, fieldtax, tax2

Or this, for each sku, sum quantity, and take average for fieldtax and tax2:

select sku, SUM(quantity), AVG(fieldtax), AVG(tax2)
from tablename
group by sku

答案 1 :(得分:1)

You need a combination of SUM and GROUP BY.

SELECT id, sku, SUM(quantity) as quantity, SUM(fieldtax) as fieldtax, tax2 FROM tabla GROUP BY sku;

Looking at your query, you're grouping by too many different columns, no good can come from that. Only group by the columns that can have a repeated value among different rows, like the sku as you were saying.