如果存在配置,请选择第一行,否则选择NULL Row

时间:2016-11-04 07:25:10

标签: sql sql-server sql-server-2008 tsql

考虑到SQL Server 2008的一个实例,假设有一个名为@Configuration的表,它有三列:IDCodeSubCodeCodeSubCode应该没有重复的行。

现在假设另一个详细级别表@ConfigurationDetails具有重复的Code行,而子代码可以SubCode作为Null。

如果SubCode可用,则直接从详细信息表中选择AmtData,如果详细信息表中没有SubCode,则选择AmtData记录中的NULL

(注意:SubCode=NULL条目始终可用于每个配置行)

关于从哪里开始的任何想法?

e.g。 一个简单的例子...... 表

declare @Configuration TABLE ( 
      ID INTEGER IDENTITY PRIMARY KEY,
      Code VARCHAR(50),
      SubCode VARCHAR(50)


);

declare @ConfigurationDetails TABLE 
( 
    Code VARCHAR(50),
    SubCode VARCHAR(50),
    Amt MONEY,
    Data VARCHAR(123)
);


INSERT INTO @Configuration VALUES
('BR1','Sub1'),
('BR1','Sub2'),
('BR1','Sub3'),
('BR1','Sub4'),
('BR2','Sub1'),
('BR2','Sub2')

INSERT INTO @ConfigurationDetails VALUES
('BR1','Sub1',500,'BR1 Sub1 Data'),
('BR1','Sub2',600,'BR1 Sub2 Data'),
('BR1',NULL,700,'BR1 Data'),
('BR2','Sub1',500,'BR2 Sub1 Data'),
('BR2',NULL,700,'BR2 Data')


INPUT:
@SubCode  = 'Sub1', @Code = 'BR1'

OUTPUT:
Code    SubCode Amt Data
====    ======= === ====
BR1     Sub1    500 BR1 Sub1 Data

INPUT:
@SubCode  = 'Sub4', @Code = 'BR1'

OUTPUT:
Code    SubCode Amt Data
====    ======= === ====
BR1     NULL    700 BR1 Data

2 个答案:

答案 0 :(得分:0)

您应该可以使用类似

的内容
SELECT *
FROM   @Configuration c
       CROSS APPLY (SELECT TOP 1 *
                    FROM   @ConfigurationDetails cd
                    WHERE  c.Code = cd.Code
                           AND ( c.SubCode = cd.SubCode
                                  OR c.SubCode IS NULL )
                    ORDER  BY cd.SubCode DESC --Order the not null match first if it exists
                   ) CA 

答案 1 :(得分:0)

WITH cte
AS (
        SELECT  a.ID, 
                a.Code, 
                a.SubCode, 
                b.SubCode as bSubCode, 
                b.Amt, 
                b.Data,
                ROW_NUMBER() OVER(PARTITION BY a.CODE, a.SubCode ORDER BY B.SUBCODE desc) as RN
          FROM  @Configuration as a
          LEFT  JOIN @ConfigurationDetails as b ON b.Code = a.Code
                AND (a.SubCode = b.SubCode OR b.SubCode IS NULL)
        )
        SELECT * FROM cte
        where rn=1