0

我有一个从 SQL 中提取记录的 excel 电子表格。我想合并记录并对匹配记录的 qty 字段求和。我尝试将 select(sum) 和 group by 命令添加到我现有的查询中,但由于没有真正的 SQL 经验,我没有走得太远。我的表如下所示:

date.     |      tax description | tax%| tax 
1/02/2013          PST              5 %  2
1/02/2013          GST              7%   3
2/02/2013          PST             5%   2

我希望它看起来像这样:

date.     |       tax%           | tax(PST) | tax(GST)
1/02/2013       (5 +7 = )12%      2              3

2/02/2013             5%           2             0

谁能帮我查询应该是什么样子?

我对 sql 真的很陌生,我尝试按税收描述和日期进行分组,但我无法理解如何在最后合并它们

4

4 回答 4

0

您可能想要:
1. 将 PST 和 GST 记录转换为 tax(PST) 和 tax(GST) 列
2. 然后按日期 SUM() 表

步骤 1.带有附加列 tax(PST) 和 tax(GST) 的转置表,但没有按日期的 SUM:

date.     |      tax description | tax% | tax(PST)  |  tax(GST) 
1/02/2013          PST              5 %    2              0
1/02/2013          GST              7%     0              3
2/02/2013          PST              5%     2              0

您可以通过添加 tax(PST) 和 tax(GST) 列以及基于 tax_description 的条件子查询来获得这样的表,如下所示:

select date, tax description, tax%, 
       case
             when t.tax_description= 'PST' then
              t.tax
             else
              0
           end as "tax(PST)",
       case
             when t.tax_description= 'GST' then
              t.tax
             else
              0
           end as "tax(GST)"
from table t

 

第 2 步。现在转置表还带有 SUM 按日期:

date.     |   tax% | tax(PST)  |  tax(GST) 
1/02/2013      7%     2              3
2/02/2013      5%     2              0

在这里,我们只是将 SUM() 聚合按日期添加到步骤 1 中的 sql:

select date, sum(tax%) as "tax%", 
       sum(case
             when t.tax_description= 'PST' then
              t.tax
             else
              0
           end) as "tax(PST)",
       sum(case
             when t.tax_description= 'GST' then
              t.tax
             else
              0
           end) as "tax(GST)"

from table t
group by date
于 2013-10-01T11:46:04.603 回答
0
select date, sum(tax%), sum(tax)
from table
group by date
于 2013-10-01T07:30:41.273 回答
0

那么你可以使用分组...

 select date,sum (tax%), sum(tax) from table group by date
于 2013-10-01T07:31:49.690 回答
0
CREATE TABLE #TestTable (date1 VARCHAR(100), tax  int,taxper int)
GO
INSERT INTO #TestTable (date1, tax ,taxper )
SELECT '1/02/2013', 2,5
UNION ALL
SELECT '1/02/2013', 3,7
UNION ALL
SELECT '2/02/2013', 2,5
UNION ALL
SELECT '2/02/2013',10,12
UNION ALL
SELECT '2/02/2013', 20,22
GO

SELECT
date1,
'('+STUFF((
SELECT  '+ ' + convert(varchar(10),tax)
FROM #TestTable
WHERE (date1 = tbl.date1)
FOR XML PATH (''))
,1,2,'')+')='+ convert(varchar(20),sum(tax)) AS tax
,
'('+STUFF((
SELECT  '+ ' + convert(varchar(10),taxper)
FROM #TestTable
WHERE (date1 = tbl.date1)
FOR XML PATH (''))
,1,2,'')+')='+ convert(varchar(20),sum(taxper)) AS taxper

FROM #TestTable tbl
GROUP BY date1
GO
DROP TABLE #TestTable
GO
于 2013-10-01T08:03:23.107 回答