使用CTE模拟Excel的vlookup

时间:2016-01-20 15:49:18

标签: sql sql-server sql-server-2008 sql-server-2012 common-table-expression

可以使用以下方法从Excel模拟vlookup函数:

select b.col, (case when a.val is NULL then 'FALSE' else 'TRUE' end)
from b left outer join
     (select distinct a.val
      from a
     ) a
     on b.col = a.val;

然后可以嵌套多个CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

问题:如何使用ct1.colct2.col代替a.col and b.col从第一个示例执行vlookup?我尝试在两个查询输出之间执行vlookup,而不将它们存储到临时表或表中。

我在考虑这样的事情:

; with cte1 as ( select pd.value as value from pentd pd
inner join aster a on a.aid = pd.aid
where pid = 10
and a.name = 'ls'),
with cte2 as( select pd.value as value from pentd pd
inner join aster a on a.aid = pd.aid
where pid = 15
and a.name = 'ls' )

select (select value from cte2),
(case 
when cte1.value is null then 'FALSE' else 'TRUE' end)
from cte2
left outer join
(select distinct value from cte1) cte1
on cte1.value = cte2.value

但这回到我身上(当然上面的代码只是一个例子,无法链接真实数据或输出)

  

Msg 512,Level 16,State 1,Line 1 Subquery返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

任何想法,如果我想要实现的是可能的,如果是,那么如何在避免错误的同时将其用于多个值?

我使用的是SQL Server 2012,但我也对SQL Server 2008解决方案感兴趣。

cte1 - 此处使用的列与连接,因为我只选择值

aid     name     value
10       ls      123.123
10       ls      422.433
10       ls      56.32

cte2 - 此处使用的列与联接,因为我只选择值

aid     name     value
15      ls       123.123
15      ls       34.21
15      ls       21.256

预期输出

value
123.123

1 个答案:

答案 0 :(得分:2)

select (select value from cte2),

这一行是你的问题。嵌套查询(括号中的位)返回多个值。您不能选择表(意味着多行)作为单个列。试试这个:

select cte2.value,
(case 
when cte1.value is null then 'FALSE' else 'TRUE' end)
from cte2
left outer join
(select distinct value from cte1) cte1
on cte1.value = cte2.value

如果您需要过滤掉重复项,或者将select distinct cte2.value选项迁移到您的CTE,则可以将其更改为distinct