用于合并行的SQL查询

时间:2013-10-01 07:24:15

标签: sql

我有一个excel电子表格,它从SQL中提取记录。我想结合记录并总结匹配记录的数量字段。我尝试将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 个答案:

答案 0 :(得分:0)

select date, sum(tax%), sum(tax)
from table
group by date

答案 1 :(得分:0)

你可以使用group by ...

 select date,sum (tax%), sum(tax) from table group by date

答案 2 :(得分: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

答案 3 :(得分:0)

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

第1步。带有附加列税(PST)和税(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_description的条件子查询的税(PST)和税(GST)列来获得此类表格,如下所示:

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