在where子句中分配select语句

时间:2014-05-21 23:45:47

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

我想知道这样做是否合法?

select coalesce(myField, (select myfield2 from table1))
from table2

我一直试图让这句话工作几个小时:

 select 
 coalesce( a.TransactionCurrencyId,

            (
            select c.TransactionCurrencyId
            from CRM_accountbase c
            join crm_pricelevelbase a
            on c.defaultpricelevelid=a.pricelevelid
            where a.pricelevelid=(
                            select a.DefaultPriceLevelId 
                            from
                                 (
                                     select a.DefaultPriceLevelId,c.iCompanyId
                                     from crm_accountbase a
                                     join onyx..company C
                                     on c.iCompanyId=a.accountnumber
                                 ) a
                                 where a.iCompanyId=c.iCompanyId
                                 ) 
            ) TransactionCurrencyId
 from mytable a

问题不在于逻辑。这是语法。

可以在合并内部使用select语句,在where条件中使用另一个select语句吗?

1 个答案:

答案 0 :(得分:2)

是的,可以选择coalesce内部和where语句内部(如果你正在比较相等性,它们只返回一行)。

请参阅代码底部附近的内联评论。

此外,它不是一个语法问题,但最好不要将三个不同的表别名为' a'。

select 
 coalesce( a.TransactionCurrencyId,
            (
                 select c.TransactionCurrencyId
                 from CRM_accountbase c
                 join crm_pricelevelbase a
                 on c.defaultpricelevelid=a.pricelevelid
                 where a.pricelevelid=(
                            select a.DefaultPriceLevelId 
                            from
                                 (
                                     select a.DefaultPriceLevelId,c.iCompanyId
                                     from crm_accountbase a
                                     join onyx..company C
                                     on c.iCompanyId=a.accountnumber
                                 ) a 
                              where a.iCompanyId=c.iCompanyId
                              ) 
            ) --TransactionCurrencyId   <--Need to not alias the subquery here
          )  --< Need to add this parenthesis
 from mytable a
相关问题