帮助创建SQL SELECT语句

时间:2010-08-18 15:02:19

标签: sql select

我在表格中有以下格式的数据:

Acct#    Amount
123      3.4 
123T     4.5 
124      2.3 
124T     4.5 
125      1.2 
125T     2.4 

如何创建一个select语句,将帐号总计为123 + 123T,并提供以下输出:

123    7.9
124    6.8
125    3.6

3 个答案:

答案 0 :(得分:5)

你没有说任何特定的SQL方言

SELECT LEFT(Acct#,3), SUM(Amount)
FROM yourTable
GROUP BY LEFT(Acct#,3)

或处理任意长度的帐号

SELECT
         CASE
                  WHEN Acct# LIKE '%T'
                  THEN SUBSTRING(Acct#,1,LEN(@Acct)-1)
                  ELSE Acct#
         END,
         SUM(Amount)
FROM     yourTable
GROUP BY
         CASE
                  WHEN Acct# LIKE '%T'
                  THEN SUBSTRING(Acct#,1,LEN(@Acct)-1)
                  ELSE Acct#
         END

或者,处理任意映射的更通用方法可能是构造一个可以随后加入的映射表。关于需要应用的规则,这里有很多缺少的信息!

SELECT d.b, SUM(yt.Amount)
FROM yourTable yt
join (
        SELECT '123' as a, '123' as b UNION ALL
        SELECT '123T' as a, '123' as b UNION ALL
        SELECT '124' as a, '124' as b UNION ALL
        SELECT '124T' as a, '124' as b UNION ALL
        SELECT '125' as a, '125' as b UNION ALL
        SELECT '125T' as a, '125' as b
) d ON d.a = yt.Acct#
GROUP BY d.b

答案 1 :(得分:1)

您也可以尝试

SELECT REPLACE([Acct#],'T', ''), SUM(Amount) 
FROM Acct
GROUP BY REPLACE([Acct#],'T', '') 

测试数据

create table acct
([acct#] varchar(10),
amount decimal(10,2)
)

insert into acct([acct#], amount) values ('123', 3.4 )
insert into acct([acct#], amount) values ('123T', 4.5 )
insert into acct([acct#], amount) values ('124', 2.3)
insert into acct([acct#], amount) values ('124T', 4.5)
insert into acct([acct#], amount) values ('125', 1.2)
insert into acct([acct#], amount) values ('125T', 2.4)

答案 2 :(得分:1)

我会这样做的:

select b.acct#, (a.Amount + b.Amount) as Amount FROM yourTable as a inner join yourTable as b
ON a.acct# = b.acct# + 'T'