我想和表Salevolume一起加入表Saleperson。联接的逻辑是:
表Saleperson有关键:itemfrom和itemto,表Salevolume有Key:Item。当Salevolume的关键“项目”在销售人员的关键“itemfrom”和“itemto”之间时,我将由销售人员制作salevolume,group of sume
密钥“accountfrom”和“accountto”和“item”最后有一些时间字符
你能帮帮我吗?
由于
CREATE TABLE [dbo].[Saleperson](
[Saleperson] [nvarchar](3) NULL,
[itemfrom] [nvarchar](4) NULL,
[itemto] [nvarchar](4) NULL
)
insert into [dbo].[Saleperson]
values
('A','111H','112H'),
('B','122G','125G'),
('C','134F','137F'),
('D','117','119'),
CREATE TABLE [dbo].[Salevolume](
[Item] [nvarchar](6) NULL,
[Salevolume] [int] NULL
)
insert into [dbo].[Salevolume]
values
('112H',30),
('113H',40),
('122G',30),
('134F',50),
('118',100)
答案 0 :(得分:0)
您需要先检查项目的最后一个字符是否为字母。如果是字母表,则检查项目的数值和字母值是否介于itemfrom和itemto的数值和字母值之间,如下所示:
select p.Saleperson,sum(v.Salevolume)
from Saleperson p
inner join Salevolume v
on v.Item between p.itemfrom and p.itemto
OR (
RIGHT(v.Item,1) between 'A' and 'Z'
and RIGHT(v.Item,1) between RIGHT(p.itemfrom,1) AND RIGHT(p.itemto,1)
and REPLACE(v.item,RIGHT(v.Item,1),'') between REPLACE(p.itemfrom,RIGHT(p.itemfrom,1),'') and REPLACE(p.itemto,RIGHT(p.itemto,1),'')
)
group by p.Saleperson;