Sql Oderconflict
我尝试创建一个视图。我有两张像这样的桌子Sql Oderconflict,sql,sql-server,sql-server-2008-r2,Sql,Sql Server,Sql Server 2008 R2,我尝试创建一个视图。我有两张像这样的桌子 ID | FileName | PathId ---------------------- 1 | Setup.exe | 2 2 | Test.doc | 1 ID | Path | ---------------- 1 | C:\\ | 2 | D:\\ | 我想按以下方式合并这两个表 ID | FileName | Path |Combined ----------------------
ID | FileName | PathId
----------------------
1 | Setup.exe | 2
2 | Test.doc | 1
ID | Path |
----------------
1 | C:\\ |
2 | D:\\ |
我想按以下方式合并这两个表
ID | FileName | Path |Combined
----------------------
1 | Setup.exe | D:\\ | D:\\Setup.exe
2 | Test.doc | c:\\ | C.\\Text.Doc
我的尝试如下所示:
SELECT TOP (100) PERCENT dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, dbo.Paths.Path + dbo.Files.FileName AS Combined
FROM dbo.Files INNER JOIN dbo.Paths
ON dbo.Files.PathID = dbo.Paths.ID
ORDER BY dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, Combined
这不起作用,因为Sqlserver会中止,并显示错误消息“Order BY term的第4列存在Orderconflict”
谁能帮帮我,告诉我我做错了什么?
提前通知。使用
SELECT TOP (100) PERCENT dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, dbo.Paths.Path + dbo.Files.FileName AS Combined
FROM dbo.Files INNER JOIN dbo.Paths
ON dbo.Files.PathID = dbo.Paths.ID
ORDER BY dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, (dbo.Paths.Path + dbo.Files.FileName );
“Combined”是在此范围内无法识别的已分配变量(别名)。其中,在下面的查询中,它将起作用,因为变量“Combined”将在范围内
SELECT FILENAME, PATHID, PATH, COMBINED FROM
(
SELECT TOP (100) PERCENT dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, dbo.Paths.Path + dbo.Files.FileName AS Combined
FROM dbo.Files INNER JOIN dbo.Paths
ON dbo.Files.PathID = dbo.Paths.ID
ORDER BY dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, (dbo.Paths.Path + dbo.Files.FileName );
) ORDER BY FILENAME, PATHID, PATH, COMBINED
不能在order by语句中使用别名。SQL Server还不知道组合的文件名实际上是dbo.Path.Path+dbo.Files.FileName。如果要按组合的值排序,则需要编写表列或使用公共表表达式,然后按新列排序
SELECT TOP (100) PERCENT dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, dbo.Paths.Path + dbo.Files.FileName AS Combined
FROM dbo.Files INNER JOIN dbo.Paths
ON dbo.Files.PathID = dbo.Paths.ID
ORDER BY dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, (dbo.Paths.Path + dbo.Files.FileName)
或
没有列
组合
而是放置现有列dbo.Paths.Path,dbo.Files.FileName
但是,由于文件名和路径已在orderby条件中,orderby是否需要(路径+文件名)?
with cte as
(
SELECT TOP (100) PERCENT dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, dbo.Paths.Path + dbo.Files.FileName AS Combined
FROM dbo.Files INNER JOIN dbo.Paths
ON dbo.Files.PathID = dbo.Paths.ID
ORDER BY dbo.Files.FileName, dbo.Files.PathId, dbo.Paths.Path, (dbo.Paths.Path + dbo.Files.FileName)
)
ORDER BY FileName, PathId, Path, Combined