Sql server 子查询为单个列筛选返回了1个以上的值错误
我有两列[2014席]和[2015席],我只需要2015年6月的值(不要管列的名称,值可以为空),但其余的列需要为全年(2014年)取值。我尝试了下面的查询,它发现子查询返回了超过1个值的错误。非常感谢您的帮助,谢谢Sql server 子查询为单个列筛选返回了1个以上的值错误,sql-server,subquery,filtering,Sql Server,Subquery,Filtering,我有两列[2014席]和[2015席],我只需要2015年6月的值(不要管列的名称,值可以为空),但其余的列需要为全年(2014年)取值。我尝试了下面的查询,它发现子查询返回了超过1个值的错误。非常感谢您的帮助,谢谢 select [First Name], [Last Name], (select [2014 Seats] from dbo.Combined2 where [ReportMonth2] between '2015-06-01' and '2
select
[First Name], [Last Name],
(select [2014 Seats]
from dbo.Combined2
where [ReportMonth2] between '2015-06-01' and '2015-06-30') as Seats_2014,
(select [2015 Seats]
from dbo.Combined2
where [ReportMonth2] between '2015-06-01' and '2015-06-30') as Seats_2015
from
dbo.Combined2
where
Region = 'NAM' and
[FTE Status] = 'Active' and
[ReportMonth2] between '2014-01-01' and '2014-12-31'
我不知道你想做什么,但这是一个冒险的机会
select [First Name]
,[Last Name]
from dbo.Combined2
cross apply
(
select [2014 Seats]
from dbo.Combined2
WHERE [ReportMonth2] between '2015-06-01' and '2015-06-30'
)as Seats_2014
cross apply
(
select [2015 Seats]
from dbo.Combined2
WHERE [ReportMonth2] between '2015-06-01' and '2015-06-30'
)as Seats_2015
where Region='NAM'
and [FTE Status]='Active'
and [ReportMonth2] between '2014-01-01' and '2014-12-31'
在您通知我们的查询中,这两个子查询在一行中列出了许多值,例如:
N°名字姓氏2014席2015席
约翰·保罗约翰·保罗的所有席位约翰·保罗的所有席位
保罗约翰的所有席位保罗约翰的所有席位
这就是你想要的
再次编辑:
select
[First Name], [Last Name],
Seats_2014 = STUFF((
select ', ' + [2014 Seats]
from dbo.Combined2
where [ReportMonth2] between '2015-06-01' and '2015-06-30'
ORDER BY [2014 Seats]
FOR XML PATH('')), 1, 2, ''),
Seats_2015 = STUFF((
select ', ' + [2015 Seats]
from dbo.Combined2
where [ReportMonth2] between '2015-06-01' and '2015-06-30'
ORDER BY [2015 Seats]
FOR XML PATH('')), 1, 2, '')
from
dbo.Combined2
where
Region = 'NAM' and
[FTE Status] = 'Active' and
[ReportMonth2] between '2014-01-01' and '2014-12-31'
说明:
Seats_2014 = STUFF((
-- Stuff is used to remove the first ', ' from the result
select N', ' + [2014 Seats]
-- N is the string declaration for nvarchar (used to prevent problems with strange characters) and ', ' come before each Seat
from dbo.Combined2
where [ReportMonth2] between '2015-06-01' and '2015-06-30'
ORDER BY [2014 Seats]
FOR XML PATH(N'')), 1, 2, N''),
--for xml path do the concatenation trick, the 1,2 is how many characters will be removed from tab (', '), in this casse one ',' and one ' ' and trade for N''
还要看到2014年和2015年这条线是一样的,对吗?
其中,[ReportMonth2]介于“2015-06-01”和“2015-06-30”之间
你想做什么?这个查询根本没有任何意义。我正在尝试提取2014席和2015席的列值,仅提取2015年6月的列值,但需要考虑2014年全年的其余列。表名是组合的2您没有提供足够的信息来进行猜测。这将是一个很好的起点。嗨,肖恩,谢谢你的查询,我已经编辑了这个问题,这样可以更清楚地理解它。请告诉我你不理解问题的哪一部分,我尝试了上面的查询,它只返回一个值多次我不知道这是否行得通,但是试试吧,更多信息请查看此链接谢谢Tiago,让我试着回到您的查询Tiago,它会告诉我这个错误“将数据类型nvarchar转换为float时出错”…不确定我认为这个查询中的N“”是指数据类型的原因,请尝试google It(SQL Server FOR XML PATH),如果可以,我会尽快提供帮助。请在没有N的情况下重试