Sql别名没有给出连接的预期结果

时间:2017-01-19 11:36:19

标签: sql sql-server

这是我的SQL查询:

Select  'P'+(cast(p.Id as varchar)) as  SolrId,
(Select lp.LocaleValue where LanguageId=3 and lp.EntityId=p.Id)  as fr_Name ,
(Select lp.LocaleValue where LanguageId=2) as hi_Name,
(Select lp.LocaleValue where LanguageId=4) as nl_Name,* from Product p
LEft  Join LocalizedProperty lp on EntityId=p.Id 

我得到了这个结果actual result但是 我想获取这样的数据expected result 任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

我只会使用条件聚合:

Select 'P' + (cast(p.Id as varchar(255))) as SolrId,
       max(case when lp.LanguageId = 3 then lp.LocaleValue end) as fr_name,
       max(case when lp.LanguageId = 2 then lp.LocaleValue end) as hi_name,
       max(case when lp.LanguageId = 4 then lp.LocaleValue end) as nl_name
from Product p left join
     LocalizedProperty lp
     on lp.EntityId = p.Id 
group by p.id;

答案 1 :(得分:0)

自己加入lp并给它4个不同的别名

select lp1.LocalValue, lp2.Localvalue from lp lp1
    join lp lp2 on lp1.pId = lp2.pId
where
    lp1.Languageid = 3 and lp2.Languageid = 2

答案 2 :(得分:0)

这很好用

Select 'P' + (cast(p.Id as varchar(255))) as SolrId,(cast(p.Name as varchar(MAX))) as Name,
           max(case when lp.LanguageId = 3 then lp.LocaleValue end) as fr_name,
           max(case when lp.LanguageId = 2 then lp.LocaleValue end) as hi_name,
           max(case when lp.LanguageId = 4 then lp.LocaleValue end) as nl_name,
           max(case when lp.LanguageId = 4 then lp.LocaleValue end)  
    from Product p left join
         LocalizedProperty lp
         on lp.EntityId = p.Id 
    group by p.id,p.Name