在AS别名后使用子查询



我试图在SQL server 2019中使用别名AS后的子查询,这是我的SQL查询:

select concat(sum(labst),' kg') as (select distinct name1 from mb52 where werks='1202') from mb52 where werks='1202';

但是这个查询给出了这个错误:

消息102,级别15,状态1,行1"("附近的语法不正确。

消息156,级别15,状态1,行1关键字"from"附近的语法不正确。

我想得到这样的结果:

1202
--------------------------------------------
343979.535 kg

代替使用CCD_ 1,因为我从变量$werks中得到werks的值,我的最终SQL查询看起来是这样的:

select concat(sum(labst),' kg') as (select distinct name1 from mb52 where werks in ($werks)) from mb52 where werks in ($werks);

有人能帮我解决这个问题吗?

您可以使用类似的动态sql

declare @sql varchar(1000)
declare @name varchar(100)
declare @werks varchar(1000) = '1202, 1200'
select distinct
@name = name1 
from   mb52
where  werks = 1202

set @sql = 'select concat(sum(labst), '' kg'') as ''' + @name + ''' from mb52 where werks in (' + @werks + ')'
exec (@sql)

看看这个DBFiddle,在那里你可以自己尝试

然而,在编写时,您的查询存在一个主要问题

as (select distinct name1 from mb52 where werks in ($werks))

如果$werks 中有多个值,则可以为name1返回多个值

所以我把它改成了= 1202,就像其他答案一样
你的查询可能需要更像这个

set @sql2 = 'select concat(sum(labst), '' kg'') as ''' + @name + ''' from mb52 where werks = 1202'

我又把in $werks改成了= 1202,因为我认为这会产生错误的结果,但这取决于你
看着dbfiddle,玩它,直到它满足你的需要。

编辑

正如评论中所要求的,以下是$werks 中只有一个值的查询外观

set @sql2 = 'select concat(sum(labst), '' kg'') as ''' + @name + ''' from mb52 where werks = ' + @werks

DBFiddle也改变了

您应该使用动态sql来获得此工作

DECLARE @S NVARCHAR(MAX)
SELECT distinct @S = 'select concat(sum(labst),'' kg'') as '+ name1 +' from mb52 where werks=''1202''' from mb52 where werks='1202'
EXEC (@S)

要做到这一点,您需要使用一个动态查询像这样:

DECLARE @query NVARCHAR(MAX) = 'select concat(sum(t1.labst),'' kg'') as '+  (SELECT DISTINCT
t1.name1  FROM dbo.mb52 t1  WHERE t1.werks = '1202') + ' from dbo.mb52 t1 where    t1.werks=''1202'''
EXEC sp_executesql @query

最新更新