求一个SQL语句

czx33859066 2017-02-28 04:36:01
表A 号码段表
批次 起始 终止
A 0001 0015
A 0021 0033
B 0001 0055

表B 号码对应关系表

原批次 原号码 新批次 新号码
A 0008 A 0009
A 0010 A 0011
A 0025 A 0028
B 0025 B 0044
B 0027 B 0054

sql的结果:
批次 起始 终止 小计 原批次 原号码 新批次 新号码 关系小计 正常小计
A 0001 0015 15 A 0008 A 0009 2 13
A 0001 0015 15 A 0010 A 0011 2 13
A 0021 0033 13 A 0025 A 0028 1 12
B 0001 0055 55 B 0025 B 0044 2 53
B 0001 0055 55 B 0027 B 0054 2 53
...全文
270 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xxfvba 2017-03-01
  • 打赏
  • 举报
回复
;WITH A(Batch,F,T)AS( SELECT 'A','0001','0015' UNION SELECT 'A','0021','0033' UNION SELECT 'B','0001','0055'), B(o_Batch,o_no,n_Batch,n_No)AS( SELECT 'A','0008','A','0009' UNION SELECT 'A','0010','A','0011' UNION SELECT 'A','0025','A','0028' UNION SELECT 'B','0025','B','0044' UNION SELECT 'B','0027','B','0054') select A.*,CONVERT(int,T)-convert(int,F)+1,b.*,COUNT(*) over(partition by a.batch,a.f), CONVERT(int,T)-convert(int,F)+1-COUNT(*) over(partition by a.batch,a.f) from A,B where a.Batch=b.o_batch and b.o_no between a.f and a.t
道素 2017-03-01
  • 打赏
  • 举报
回复

;WITH A(Batch,F,T)AS(
    SELECT 'A','0001','0015' UNION
    SELECT 'A','0021','0033' UNION
    SELECT 'B','0001','0055'
),B(o_Batch,o_no,n_Batch,n_No)AS(
    SELECT 'A','0008','A','0009' UNION
    SELECT 'A','0010','A','0011' UNION
    SELECT 'A','0025','A','0028' UNION
    SELECT 'B','0025','B','0044' UNION
    SELECT 'B','0027','B','0054'
)
SELECT a.*,t1-f1+1 AS subTotal,b.*,COUNT(0)OVER(PARTITION BY a.Batch,a.F,a.T) ,t1-f1+1-COUNT(0)OVER(PARTITION BY a.Batch,a.F,a.T)
FROM a
CROSS APPLY(VALUES(CONVERT(INT,T),CONVERT(INT,F))) c(t1,f1)
LEFT JOIN B ON a.Batch=b.o_Batch AND CONVERT(INT,b.o_no) BETWEEN c.f1 AND c.t1

Batch F    T    subTotal    o_Batch o_no n_Batch n_No             
----- ---- ---- ----------- ------- ---- ------- ---- ----------- -----------
A     0001 0015 15          A       0008 A       0009 2           13
A     0001 0015 15          A       0010 A       0011 2           13
A     0021 0033 13          A       0025 A       0028 1           12
B     0001 0055 55          B       0025 B       0044 2           53
B     0001 0055 55          B       0027 B       0054 2           53
昵称被占用了 2017-02-28
  • 打赏
  • 举报
回复
with cte as (
select a.批次,a.起始,a.终止,cast(a.终止 as int)-cast(a.起始 as int) as 小计,counr(b. 新号码 ) as 关系小计 
from a left join b
on b.原批次 = a.批次 and  b.原号码 between a. 起始 and a.终止
group by a.批次,a.起始,a.终止
)
select a.*
     ,b.*
     ,a.小计 - a.关系小计 as 正常小计
from cte as aleft join b
on b.原批次 = a.批次 and  b.原号码 between a. 起始 and a.终止

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧