我正在进行查询,我在分区内使用行号,我想使用CONCAT组合多个字段来构建全名。当我只是将字段和+一起添加为All Good。当我尝试使用CONCAT函数时 - 我收到一条错误消息。我不太明白为什么 - 有人可以告诉我是否允许在汇总中使用它?
以下是可以正常使用的代码:
USE [AdventureWorks2012]
SELECT
count([BusinessEntityID])as NumPeople
,[PersonType]
,max(case when rnum = 1 then [BusinessEntityID] end) as '1st ID'
,max(case when rnum = 2 then [BusinessEntityID] end) as '2nd ID'
,max(case when rnum = 1 then [FirstName]+' '+[LastName] end ) as '1st FullName'
,max(case when rnum = 2 then [FirstName]+' '+[LastName] end ) as '2nd FullName'
from
(
Select *, row_number() over (partition by [PersonType] order by [BusinessEntityID]) as rnum
FROM
[Person].[Person]
) x
group by [PersonType]
及其输出:
+-----------+------------+--------+--------+----------------+------------------+
| NumPeople | PersonType | 1st ID | 2nd ID | 1st FullName | 2nd FullName |
+-----------+------------+--------+--------+----------------+------------------+
| 273 | EM | 1 | 2 | Ken Sánchez | Terri Duffy |
| 289 | GC | 2091 | 2092 | David Ortiz | Qiang Wang |
| 18484 | IN | 1699 | 1700 | David Robinett | Rebecca Robinson |
| 753 | SC | 291 | 293 | Gustavo Achong | Catherine Abel |
| 17 | SP | 274 | 275 | Stephen Jiang | Michael Blythe |
| 156 | VC | 1491 | 1493 | Paula Moberly | Suchitra Mohan |
+-----------+------------+--------+--------+----------------+------------------+
这是给出错误的代码:
USE [AdventureWorks2012]
SELECT
count([BusinessEntityID])as NumPeople
,[PersonType]
,max(case when rnum = 1 then [BusinessEntityID] end) as '1st ID'
,max(case when rnum = 2 then [BusinessEntityID] end) as '2nd ID'
,max(case when rnum = 1 then (concat(p.[FirstName], stuff(p.[MiddleName],1,0,' '), stuff(p.[LastName],1,0,' ') end ) as '1st FullName'
,max(case when rnum = 2 then (concat(p.[FirstName], stuff(p.[MiddleName],1,0,' '), stuff(p.[LastName],1,0,' ')end ) as '2nd FullName'
from
(
Select *, row_number() over (partition by [PersonType] order by [BusinessEntityID]) as rnum
FROM
[Person].[Person]
) x
group by [PersonType]
这是错误:
Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'end'.
Msg 102, Level 15, State 1, Line 17
Incorrect syntax near 'x'.
我确信这只是Microsoft SQL Server不允许的内容 - 但我想知道它无法完成的内容 - 这样我就可以确保在我完成时避免使用它需要。或者,如果有某种方法可以做到这一点,那么它也会很棒......
答案 0 :(得分:1)
我认为括号是这里唯一的问题。使用concat
的两行与...) end) as '...
类似,它们应该像...))) end) as '...
一样读取。完整查询如下。
USE [AdventureWorks2012]
SELECT
count([BusinessEntityID])as NumPeople
,[PersonType]
,max(case when rnum = 1 then [BusinessEntityID] end) as '1st ID'
,max(case when rnum = 2 then [BusinessEntityID] end) as '2nd ID'
,max(case when rnum = 1 then (concat(p.[FirstName], stuff(p.[MiddleName],1,0,' '), stuff(p.[LastName],1,0,' '))) end) as '1st FullName'
,max(case when rnum = 2 then (concat(p.[FirstName], stuff(p.[MiddleName],1,0,' '), stuff(p.[LastName],1,0,' '))) end) as '2nd FullName'
from
(
Select *, row_number() over (partition by [PersonType] order by [BusinessEntityID]) as rnum
FROM
[Person].[Person]
) x
group by [PersonType]