Sql查询根据TaxType代码获取Amounts的总和

时间:2011-07-29 08:29:02

标签: sql-server-2008

我的表格数据如下

EmpID    FedTaxID    TaxTypeCode   Amount
1059    888888888   TX02        2000
1059    888888888   TX02        3000
1059    888888888   TX03        5010

我使用self join根据FedTaxID and TaxTypeCode获取总金额。我写如下

SELECT SUM(t1.Amount) AS Expr1, SUM(t2.Amount) AS Expr2 FROM tblTest AS t1 CROSS JOIN tblTest AS t2 WHERE (t1.FedTaxID = '888888888') AND (t2.FedTaxID = '888888888') AND (t1.TaxTypeCode = 'tx02') AND (t2.TaxTypeCode = 'tx03')

但它返回的金额如下

 Expr1      Expr2 
 5000   10020

我的预期输出是

 Expr1      Expr2 
  5000     5010

任何人都可以告诉我哪里出错了。此外,我需要那些2的总和,所以任何人都可以帮助我

5 个答案:

答案 0 :(得分:2)

对于这类事情使用“CASE”声明要好得多:

SELECT FedTaxId, SUM(tx02t) as tx02_tot , SUM(tx03t) as tx03tot , SUM(Txallt) as txnntot
  FROM (SELECT CASE WHEN  TaxTypeCode = 'tx02' THEN Amount else 0 END as tx02t,
               CASE WHEN  TaxTypeCode = 'tx03' THEN Amount else 0 END as tx03t,
               Amount as txallt
        FROM tbltest
        WHERE FedTaxID = '888888888'
       ) 
GROUP BY FedTaxId

答案 1 :(得分:1)

我没有方便的SQL实例来检查我的语法,但您可以使用PIVOT执行此操作:

Select ['TX02'], ['TX03']
FROM
(
    Select TaxTypeCode, Sum(Amount) as Total
    From tblTest
    Group By TaxTypeCode
) as SourceTable
PIVOT
(
Sum(Total)
FOR TaxTypeCode IN (['TX02'], ['TX03'])
) AS PivotTable

更新: 使用FedTaxID(再次,有一点点,我现在没有办法检查这个):

Select ['TX02'], ['TX03']
FROM
(
    Select FedTaxID, TaxTypeCode, Sum(Amount) as Total
    From tblTest
    Group By FedTaxID, TaxTypeCode
) as SourceTable
PIVOT
(
Sum(Total)
FOR TaxTypeCode IN (['TX02'], ['TX03'])
) AS PivotTable

答案 2 :(得分:1)

只需做一个简单的GROUP BY并使用WITH ROLLUP作为总计:

SELECT 
    TaxTypeCode, SUM(Amount) 
FROM 
    tblTest 
WHERE
    FedTaxID = '888888888'
    AND TaxTypeCode IN ('TX02', 'TX03')
GROUP BY
    TaxTypeCode WITH ROLLUP

应该给你一个这样的输出:

 TaxTypeCode    (No column name)
    TX02           5000
    TX03           5010
    NULL          10010              -- this is the line with the totals

答案 3 :(得分:0)

您将值加起来两次,所以expr1 = 2000 + 3000 = 5000

但是expr你也加了两次,所以5010 + 5010 = 10020

Tjeu

答案 4 :(得分:0)

您的交叉联接会导致返回两行数据,如下所示

2000 5010
3000 5010

所以,如果你总结一下,你会得到你所看到的结果。

我确信这不是最佳方式,但子查询可以正常工作。