所以我有一张桌子可以确定分支的区域代码,具体取决于月,
让我们来自January to february it's Region code would be 1,
from February to March it would be 2
和for the month of april upto date would be 3
所以这是表格的样本外观
我有一个从表中获取数据的代码,但我想要实现的是,如果所选数据的LoanDate在上面的日期内(在fld_Datefrom和fld_Dateto之间),它将使用指示的fld_BranchRegion以上。 (例如,日期的Loandate为2013-01-12 00:00:00
,如上所示,它将使用RegionCode 4A ,如果数据为2013-02-04 00:00:00
,则会使用区域代码 3
这是我使用的代码
SELECT
TE.LOAN
,bp.REGION
,BP.ID
,TE.AMOUNT
,te.ID
FROM #TrackExpired TE
inner join Transactions.TBLMAIN PM
on TE.ID = PM.ID
inner join #track BP
on BP.ID=cast(TE.ID/1000000000000 as decimal(38,0))
WHERE ((cast(TE.EXPIRATION as date) < cast(TE.newloandate as date))
OR(TE.NewLoanDate is null and (cast(TE.EXPIRATION as date) < cast(PM.REDEEMED as date))) or ((TE.NewLoanDate is null and PM.REDEEMED is null) and (PM.STATUS = 7 or PM.STATUS = 5)) )
这个问题是它生成重复值,所以我在 #track 表中有3次出现日期,数据的数量也输出3次,区别代码不同!! / p>
我希望从**#track 中选择区域代码,而不是输出它们。 根据数据的贷款日期。**
我只是希望实现这一点而不是输出所有区域代码,它只使用基于提供的 #track 表的范围之间的区域代码。
任何帮助?或其他方法?谢谢!。对不起,我是SQL新手。
编辑这里是创建临时表的代码。
#trackexpired
SELECT PH.ID
,PH.LOAN
,PH.EXPIRATION
,PH.AMOUNT
,(SELECT T3.LOAN FROM Transactions.HISTO T3 INNER JOIN
(
SELECT MIN(T2.ID) as pawnhisto
FROM Transactions.HISTO T2
WHERE T2.ID > PH.ID
AND PH.ID = T2.ID
) T4
ON T4.pawnhisto = T3.ID
)as 'NewLoanDate'
INTO #TrackExpired
FROM Transactions.HISTO PH
INNER JOIN Transactions.MAIN PM
ON PM.ID=PH.ID
WHERE YEAR(PH.LOAN) = @YEAR
#track
Select bt.CODE
,bp.ID
,AREA
,REGION
,NCODE
,FROM
,isnull(fld_Dateto,GETDATE()) as fld_Dateto
into #sort
from Transactions.tbl_BranchTracking bt
inner join Reference.tbl_BranchProfiles bp
on bt.CODE = bp.CODE
Select * into #track from #sort
where @YEAR >= year(FROM)
and
@YEAR <= year(fld_Dateto)
答案 0 :(得分:1)
测试数据
create table #LoanTable (
ID int not null,
RegionCode nvarchar(50) not null,
LoanDate datetime not null
);
insert into #LoanTable values
(1,'5','10/01/2014'),
(2,'5','10/18/2014'),
(3,'5','10/02/2014'),
(4,'3','04/11/2014'),
(5,'3','04/05/2014'),
(6,'4A','01/09/2014'),
(7,'4A','01/05/2014')
create table #LoanDetailsTable (
ID int not null,
LoanAmount INT not null,
LoanDate datetime not null
);
insert into #LoanDetailsTable values
(1,5000,'10/15/2014'),
(2,1000,'10/11/2014'),
(3,2000,'10/09/2014'),
(4,1500,'04/13/2014'),
(5,5000,'04/17/2014'),
(6,500,'01/19/2014'),
(7,2500,'01/15/2014')
<强>查询强>
;With RegCode
AS
(
SELECT RegionCode, MAX(MONTH(LoanDate)) [Month]
FROM #LoanTable
GROUP BY RegionCode
)
SELECT LDT.* , RC.RegionCode
FROM #LoanDetailsTable LDT INNER JOIN RegCode RC
ON MONTH(LDT.LoanDate) = RC.[Month]
<强>结果
ID LoanAmount LoanDate RegionCode
1 5000 2014-10-15 00:00:00.000 5
2 1000 2014-10-11 00:00:00.000 5
3 2000 2014-10-09 00:00:00.000 5
4 1500 2014-04-13 00:00:00.000 3
5 5000 2014-04-17 00:00:00.000 3
6 500 2014-01-19 00:00:00.000 4A
7 2500 2014-01-15 00:00:00.000 4A
使用CTE提取日期的月份部分以及与之关联的区域代码,然后将其与贷款日期月份的数据表和cte中提取的月份一起加入,并获取当时的区域代码。快乐的日子:))