0
我在做一個查詢,我在分區內使用行號,我想用CONCAT來組合幾個字段來構造一個全名。當我只是將這些字段添加到+它是一切正常。當我嘗試使用CONCAT功能時 - 我收到一條錯誤消息。我不明白爲什麼 - 有人可以告訴我這是不是允許在一個聚合內?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不允許的東西 - 但我想知道它是什麼,無法完成 - 所以我可以確保在需要時避免這種情況。或者如果有某種方法可以做到這一點,那麼這將是偉大的...
謝謝!這個伎倆。做這樣一個簡單的錯誤讓我感到非常愚蠢。但是我想如果你沒有犯錯誤,你還沒有學習...... – kiltannen