SELECT DATA_ID, SPEC_ID FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY DATA_ID ORDER BY RNK) as RN from (
select 1 as RNK, B.DATA_ID, A.SPEC_ID
from A JOIN B ON
(B.C1_Temp >= A.C1_Minimum and B.C1_Temp <= A.C1_Maximum and B.R1_Temp >=
A.R1_Minimum and B.R1_Temp <= A.R1_Maximum )
UNION ALL
select 2 as RNK, B.DATA_ID, A.SPEC_ID
from A JOIN B ON
(B.C1_Temp >= A.C1_Minimum and B.C1_Temp <= C1_Maximum)
UNION ALL
select 3 as RNK, B.DATA_ID, A.SPEC_ID
from A JOIN B ON
(B.R1_Temp >= A.R1_Minimum and B.R1_Temp <= R1_Maximum)
) a
) a
WHERE RN = 1
※ 引述《ashin42 (Second)》之铭言:
: 举个例子好了 比较好理解
: A Table定义SPEC
: SPEC_ID C1_Minimun C1_Maximun R1_Minimun R1_Maximun
: 1 1 3 0 0
: 2 4 6 0 0
: 3 4 6 9 12
: 4 0 0 9 12
: B Table 定义计算完的结果值
: DATA_ID C1_Temp R1_Temp
: 1 5 10 ===> SPEC_ID = 3 , C1和R1两者都符合SPEC,SPEC3优先2
: 2 5 5 ===> SPEC_ID = 2 , C1符合SPEC
: 3 2 11 ===> SPEC_ID = 1 , C1优先于R1,SPEC_ID 1优先4
: 4 7 11 ===> SPEC_ID = 4 , R1符合SPEC
: ※ 引述《ashin42 (Second)》之铭言:
: : 数据库名称: MS SQL SERVER 2017
: : 数据库版本: v17.9.1
: : 内容/问题描述:
: : Hi 各位前辈早
: : 我目前遇到了一个SQL的问题 , 我在资料表A定义了两个参数的最大(C1和R1的Maximun)
: : 与最小值(C1和R1的Minimum) , 资料表B则是实际的资料带有参数实际值得资料 ,
: : 我期望串出来的SQL有优先级 , 满足C1和R1的Maximun和Minimum的资料优先被找出 ,
: : 如果没有再找出满足C1的Maximun和Minimum的资料 , 如果没有再找出满足R1的Maximun和
: : Minimum的资料
: : 但如果SQL向下面这样下会有重复的问题 , 会重复找到分别符合条件的资料 , 无法过滤
: : 掉重复的
: : and (B.C1_Temp >= A.C1_Minimum and B.C1_Temp <= A.C1_Maximun and B.R1_Temp >=
: : A.R1_Minimum and B.R1_Temp <= A.R1_Maximun )
: : or (B.C1_Temp >= A.C1_Minimum and B.C1_Temp <= C1_Maximun)
: : or (B.R1_Temp >= A.R1_Minimum and B.R1_Temp <= R1_Maximun)