我正在尝试在一行而不是多行中打印结果。 我有一个查询看起来像:
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM MACHS
WHERE MACHID <> 0
EXCEPT
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM GROUPS
WHERE GROUPS.GROUPTYPE = 'M'
通过使用Except查询,我可以:
lineNumber MachName
1个WinMach2
2 WinMach6
我想拥有:
WinMach2,WinMach6
因此,为了将结果打印在一行中,我尝试了:
select stuff((SELECT DISTINCT ', ' + RTRIM(LTRIM(MACHNAME))
FROM MACHS
WHERE MACHID <> 0
EXCEPT
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM GROUPS
WHERE GROUPS.GROUPTYPE = 'M'
for xml path ('')
), 1, 2, '') as machineName
FROM GROUPS
但是,错误是:
FOR XML子句在派生的视图,内联函数中无效 表和子查询包含set运算符时。去工作 围绕,使用派生表包装包含set运算符的SELECT 语法并在其之上应用FOR XML。
如果我这样做,它就可以工作:
select stuff((SELECT DISTINCT ', ' + RTRIM(LTRIM(MACHNAME)) FROM MACHS WHERE MACHID <> 0
for xml path ('')), 1, 2, '') as machineName
FROM MACHS
结果是:
WinMach1,WinMach2,WinMach3,WinMach4, WinMach5,WinMach6,WinMach7,WinMach8, WinMach9
我检查了这个问题:SQL UNION FOR XML name output column。但是,我无法理解该修复程序。
然后我尝试了:Using UNION ALL in STUFF / XML Path 但是,当我做第一部分时:
SELECT * FROM (SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM MACHS
WHERE MACHID <> 0
EXCEPT
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM GROUPS
WHERE GROUPS.GROUPTYPE = 'M') AS K
错误是'未为'K'的第1列指定列名。
你能帮我吗?
谢谢
答案 0 :(得分:1)
您有FROM
子句。因此,您需要指定数据源-在您的情况下为AS K
,但应为DS ([k])
,这意味着数据源DS
的别名为{-{1}} :
K
最后是这样的:
SELECT *
FROM
(
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM MACHS
WHERE MACHID <> 0
EXCEPT
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM GROUPS
WHERE GROUPS.GROUPTYPE = 'M'
) DS (K);
答案 1 :(得分:1)
我改用NOT EXISTS
:
select stuff( (select distinct ',' +rtrim(ltrim(m.MACHNAME))
from MACHS m
where MACHID <> 0 and
not exists (select 1
from GROUPS g
where g.MACHNAME = m.MACHNAME and
g.GROUPTYPE = 'M'
) for xml path ('')
), 1, 1, ''
) as MachName