显示不同的值并使用sql server对值进行求和

时间:2015-04-06 14:45:02

标签: sql sql-server

在下面的代码中,我有一个查询,我想显示像这样的值。我想显示不同的税收计算,并根据独特的税收计算总价格的总和。请帮助我这样做。

发票明细表:

TaxCalculation TotalPrice

 0.00            500
 0.00            750
 1.00            980
 2.00            400

预期结果:

TaxCalculation TotalPrice

 0.00            1250
 1.00            980
 2.00            400



SELECT DISTINCT CONVERT(VARCHAR(10), I.CreatedOn, 105) AS InvoiceDate
    ,INVD.Interest
    ,CASE 
        WHEN Count(INVD.TaxCalculation) OVER (PARTITION BY INVD.TaxCalculation) > 1
            THEN SUM(Isnull((INVD.TotaPrice), 0.00))
        ELSE Isnull((INVD.TotaPrice), 0.00)
        END VATAMOUNT
    ,INVD.TaxCalculation
    ,INVD.TotaPrice
FROM Invoice I
LEFT OUTER JOIN Customer C 
    ON C.CustomerID = I.CustomerID
LEFT OUTER JOIN InvoiceDetail INVD 
    ON INVD.InvoiceID = I.InvoiceID
LEFT OUTER JOIN Locations L 
    ON L.LocationID = I.LocationID
LEFT OUTER JOIN LocationProductMap LPM 
    ON LPM.ProductID = INVD.ProductID
LEFT OUTER JOIN OrderForm O 
    ON O.OrderFormID = I.OrderFormID
LEFT OUTER JOIN Product P 
    ON P.ProductID = INVD.ProductID
LEFT OUTER JOIN UnitType U 
    ON U.UnitTypeID = P.UnitTypeID
WHERE I.InvoiceID = @i_InvoiceID
    AND LPM.LocationID = I.LocationID
GROUP BY I.TotalPrice
    ,CONVERT(VARCHAR(10), I.CreatedOn, 105)
    ,INVD.Interest
    ,INVD.TaxCalculation
    ,INVD.TotaPrice

2 个答案:

答案 0 :(得分:1)

这是我将查询用作子查询的地方

SELECT
    A.TaxCalculation 
  , SUM(A.TotaPrice) AS TotalPrice
FROM
(
  SELECT DISTINCT 
      CONVERT(VARCHAR(10), I.CreatedOn, 105) AS InvoiceDate
      , INVD.Interest
      , CASE 
          WHEN Count(INVD.TaxCalculation) OVER (PARTITION BY INVD.TaxCalculation) > 1
              THEN SUM(Isnull((INVD.TotaPrice), 0.00))
          ELSE Isnull((INVD.TotaPrice), 0.00)
          END VATAMOUNT
      , INVD.TaxCalculation
      , INVD.TotaPrice
  FROM Invoice I
  LEFT JOIN Customer C
      ON C.CustomerID = I.CustomerID
  LEFT JOIN InvoiceDetail INVD
      ON INVD.InvoiceID = I.InvoiceID
  LEFT JOIN Locations L
      ON L.LocationID = I.LocationID
  LEFT JOIN LocationProductMap LPM
      ON LPM.ProductID = INVD.ProductID
  LEFT JOIN OrderForm O
      ON O.OrderFormID = I.OrderFormID
  LEFT JOIN Product P
      ON P.ProductID = INVD.ProductID
  LEFT JOIN UnitType U
      ON U.UnitTypeID = P.UnitTypeID
  WHERE I.InvoiceID = @i_InvoiceID
      AND LPM.LocationID = I.LocationID
  GROUP BY I.TotalPrice
      , CONVERT(VARCHAR(10), I.CreatedOn, 105)
      , INVD.Interest
      , INVD.TaxCalculation
      , INVD.TotaPrice
) AS A
GROUP BY A.TaxCalculation

答案 1 :(得分:0)

以下查询给出了预期结果。

从税收

中选择不同税,来自发票组的总和(价格)

有关详细信息,请参阅以下链接:

http://sqlfiddle.com/#!6/be9ae/2

如果这不是预期的答案,请告诉我税务计算和定义的总价格的数据类型。

谢谢。