我试图在Oracle SQL查询中获取VLOOKUP功能。我在那里使用子查询select语句尝试了这个,但它没有返回任何值。
必需逻辑
Lookup_Link_Date
字段中需要VLOOKUP逻辑,然后Same_Date
字段中也使用该逻辑。
基本上在Excel中Lookup_Link_Date
字段在Link_String
字段中查找String
字段,然后返回其旁边的date
字段。
为了尝试在Oracle SQl中复制它,我创建了一个子查询选择语句,用于查找date
type = type_ref AND no = no_ref
,但它永远不会返回任何结果,我不知道为什么。
当前查询
SELECT DISTINCT
g.type AS Type,
g.no AS Number,
g.date AS Date,
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref,
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
(SELECT g.date
FROM gtable g
WHERE g.type_ref = g.type
AND g.no_ref = g.no) AS Lookup_Link_Date,
CASE WHEN (SELECT g.date
FROM gtable g
WHERE g.type_ref = g.type
AND g.no_ref = g.no) = g.date
THEN 'YES'
ELSE 'NO'
END AS Same_Date
FROM gtable g
尝试#2查询
SELECT DISTINCT
g.type AS Type,
g.no AS Number,
g.date AS Date,
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref,
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
(SELECT b.date
FROM gtable b
WHERE b.type_ref = b.type
AND b.no_ref = b.no) AS Lookup_Link_Date,
CASE WHEN (SELECT d.date
FROM gtable d
WHERE d.type_ref = d.type
AND d.no_ref = g.no) = d.date
THEN 'YES'
ELSE 'NO'
END AS Same_Date
FROM gtable g
SELECT DISTINCT
g.type AS Type,
g.no AS Number,
g.date AS Date,
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref,
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
(SELECT date
FROM gtable
WHERE type_ref = g.type
AND no_ref = g.no) AS Lookup_Link_Date,
CASE WHEN (SELECT date
FROM gtable
WHERE type_ref = g.type
AND no_ref = g.no) = g.date
THEN 'YES'
ELSE 'NO'
END AS Same_Date
FROM gtable g
答案 0 :(得分:3)
检查你的别名。无论是内部还是外部。因此,g.type_ref = g.type
和g.no_ref = g.no
据称不能比较您想要比较的内容。
SELECT DISTINCT
g.type AS Type,
g.no AS Number,
g.date AS Date,
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref,
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
(SELECT date
FROM gtable
WHERE type_ref = g.type
AND no_ref = g.no) AS Lookup_Link_Date,
CASE WHEN (SELECT date
FROM gtable
WHERE type_ref = g.type
AND no_ref = g.no) = g.date
THEN 'YES'
ELSE 'NO'
END AS Same_Date
FROM gtable g;
编辑(接受后:-)以下是如何使用自联接编写查询:
SELECT
g.type AS Type,
g.no AS Number,
g.date AS Date,
g.type_ref AS Type_Ref,
g.no_ref AS No_Ref,
g.type||g.no||g.company AS String,
g.type_ref||g.no_ref||g.company AS Link_String,
gref.date AS Lookup_Link_Date,
CASE WHEN g.date = gref.date THEN 'YES' ELSE 'NO' END AS Same_Date
FROM gtable g
LEFT JOIN gtable gref ON g.type = gref.type_ref and g.no = gref.no_ref;
(我删除了DISTINCT。是否有重复项?然后你需要它,否则不需要。)