使用Left()从多个表中选择和组合2行

时间:2013-01-31 23:02:34

标签: sql

我有这个功能做了我想要的,但只是想知道是否有办法一次性完成:

drop table ##aa
select s.storeid,cast(LEFT(p.paytype,1) as varchar(50)) as Paytype,SUM(amount) as Total
into ##aa
from RPTrs s, rpPay p
where s.storeid=p.StoreID and s.ReceiptNO=p.ReceiptNo 
and trsdate between '1/1/06' and '1/1/13'
group by s.storeid,LEFT(p.paytype,1)

update A set a.paytype=b.currencydesc
from ##aa a, Currencies b
where a.Paytype=b.POSCurrency

select * from ##aa order by Paytype, StoreID

我要问的是,我想将b.CurrencyDesc应用于初始的p.paytype。 Paytype只显示C作为示例,但我希望它代表Cash,V代表Visa,例如它在货币表中描述

1 个答案:

答案 0 :(得分:1)

好像你可以添加JOIN

select   s.storeid
       , b.currencydesc as Paytype
       , SUM(amount)    as Total
into     ##aa
from     RPTrs s

join     rpPay p
on       s.storeid=p.StoreID
     and s.ReceiptNO=p.ReceiptNo

join     Currencies b 
on       b.POSCurrency=cast(LEFT(p.paytype,1) as varchar(50))

where    trsdate between '1/1/06' and '1/1/13'
group by s.storeid
       , b.currencydesc

转换为使用显式连接语法。无法分辨哪个表格贡献trsdate。而且我不确定连接条件是否需要CAST