如何从主查询到子查询建立链接

mznpcxlj  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(402)

我将两个值从一个表插入到另一个表中。其中一个插入值来自连接三个列值。我正在使用下面的查询,但错误是“子查询有多个值”。我们不能将“top 1”包含到子查询中,因为子查询给所有值都相同。

insert into dbo.tblCrucibleLdgDtls (R2IGTNo,TotalMtrlWgt) 
Select  R2IGTNo,
   (select RTRIM(LTRIM(( CONCAT(ULTotalS1S2MtrlWgt,ULTotalS3S4MtrlWgt,ULTotalS5S6MtrlWgt)))) as TotalMtrlWgt 
    from dbo.tbl1RMWeighingDetails 
    where ULTotalS1S2MtrlWgt is not null or ULTotalS3S4MtrlWgt is not null or ULTotalS5S6MtrlWgt is not null 
   ) 
from dbo.tbl1RMWeighingDetails 
where  R2IGTNo like '%C%'

从表

解决办法可能很简单。我不是一个Maven。没有重复的和(ultotals1s2mtrlwgt,ultotals3s4mtrlwgt,ultotals5s6mtrlwgt)与r2igtno有独特的关系。就像如果r2igtno有b1,则ultotals1s2mtrlwgt有值,如果r2igtno有b2,则ultotals3s4mtrlwgt有值,如果r2igtno有b3,则ultotals5s6mtrlwgt有值。有了这个条件,查询就可以改变了。请建议。

llycmphe

llycmphe1#

为表指定别名:

SELECT ..., (SELECT ... FROM  dbo.tbl1RMWeighingDetails wdA)
FROM  dbo.tbl1RMWeighingDetails wdB
...

现在,内部/嵌套子查询可以引用 wdB ,它将表示表的外部示例。
而且,它看起来更适合使用连接、应用或窗口功能。

lp0sw83n

lp0sw83n2#

解决方案取决于从内部查询中获取的行的类型。如果内部查询返回多个重复行,则解决方案更简单,只需使用不同的-

insert into dbo.tblCrucibleLdgDtls (R2IGTNo,TotalMtrlWgt) 
Select  R2IGTNo,
           (select distinct RTRIM(LTRIM((CONCAT(ULTotalS1S2MtrlWgt,ULTotalS3S4MtrlWgt,ULTotalS5S6MtrlWgt)))) as TotalMtrlWgt 
            from dbo.tbl1RMWeighingDetails 
            where ULTotalS1S2MtrlWgt is not null or ULTotalS3S4MtrlWgt is not null or ULTotalS5S6MtrlWgt is not null 
           ) 
from dbo.tbl1RMWeighingDetails 
where  R2IGTNo like '%C%'

但是如果您的内部查询返回多个彼此不同的行,那么您必须重新访问您的需求。

pnwntuvh

pnwntuvh3#

我用cte得到了答案,在ms论坛上得到了建议

insert into dbo.tblCrucibleLdgDtls (R2IGTNo,TotalMtrlWgt) 
    Select  R2IGTNo, coalesce(ULTotalS1S2MtrlWgt,ULTotalS3S4MtrlWgt,ULTotalS5S6MtrlWgt) as TotalMtrlWgt     from dbo.tbl1RMWeighingDetails     where  R2IGTNo like '%C%'

或者

with cte1 as(
select R2IGTNo,RTRIM(LTRIM(( CONCAT(ULTotalS1S2MtrlWgt,ULTotalS3S4MtrlWgt,ULTotalS5S6MtrlWgt)))) as TotalMtrlWgt 
        from dbo.tbl1RMWeighingDetails 
        where R2IGTNo like '%C%'
        and (ULTotalS1S2MtrlWgt is not null 
        or ULTotalS3S4MtrlWgt is not null 
        or ULTotalS5S6MtrlWgt is not null))
insert into dbo.tblCrucibleLdgDtls (R2IGTNo,TotalMtrlWgt) 
select * from cte1

不管怎样,谢谢大家-香卡

相关问题