我有两个表,如果第一个表中存在数据,则用“ Y”填充标志列,如果不填充“ N”,则仅比较3列,一列是数字,第二列是名称,第三列是日期时间。但是我的商务规则案例陈述总是返回“ Y”
Table 1 (staging table, type1)
column1: number, data (123, 456,756)
column2: name, date('Mike', 'Dray','John')
column3: datetime. data('2018-12-03 14:00:52.000','2018-12-03 14:00:52.000','2018-12-03 14:00:52.000')
Table2 (landing table, type2)
column1 number, data (123, 456,756, 890)
column2: name, date('Mike', 'Dray','John','Chris')
column3: datetime. data('2018-12-03 14:00:52.000','2018-12-03 14:00:52.000','2018-12-03 14:00:52.000','2018-09-20 10:31:39.000')
column4: flagcolumn, data('Y','Y','Y','N')
因此,无论数据是否在表1中,表2中的最后第4列应填充为y / n。 我写了这样的查询:
WITH CDE AS (
SELECT T1.number,T1.name,T1.Bdatetime,
FROM dbo.db.table T1)
,CDE1 AS (
SELECT CDE.*,BUS_RULE_valid = (
select case
when EXISTS (
SELECT number, name, datetime
FROM dbo.db.table T1
WHERE number IN
(SELECT number
FROM dbo.db.table2)
AND name
(SELECT name FROM dbo.db.t2)
AND datetime IN
(SELECT datetime FROM dbo.db.t2))
THEN 'Y'
ELSE 'N'
END)
FROM CDE
)
SELECT * FROM CDE1
答案 0 :(得分:1)
您正在检查另一个表中是否分别存在三个值,这几乎总是可能的。看起来您需要检查合并的值,看起来像下面的查询。
我很乐意删除with
部分,因为这里似乎没有必要。但是您也可以保留它,解决方案将是相同的(除了使用的表别名之外)。
SELECT
T1.number_col,
T1.name_col,
T1.datetime_col,
CASE WHEN EXISTS (
SELECT 'x' FROM dbo.db.table2 T2
WHERE
t2.number_col = T1.number_col AND
t2.name_col = T1.name_col AND
t2.datetime_col = T1.datetime_col)
THEN 'Y'
ELSE 'N'
END AS BUS_RULE_valid
FROM dbo.db.table1 T1