我存储的程序如下:
alter PROCEDURE [dbo].[ParkingDeatailsReportnewstack]
@startdate NVARCHAR(100),
@enddate NVARCHAR(100)AS
BEGIN
DECLARE @cols AS NVARCHAR(MAX) , @query AS NVARCHAR(MAX)
SELECT @cols = STUFF(( SELECT DISTINCT ',' + QUOTENAME(Vtype)
FROM dbo.VType_tbl FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query =
'SELECT LocName,Date, ' + @cols + '
from (
select l.LocName,v.Vtype, convert(date, dtime) as Date
from Transaction_tbl t
join VType_tbl v on t.vtid = v.vtid
join dbo.Location_tbl l on t.locid=l.Locid
where dtime between ''' + @startdate + ''' and ''' + @enddate + ''' order by l.LocName
) d
pivot (
count(Vtype) for Vtype in (' + @cols + ')
) p '
EXEC sys.sp_executesql @query
End
我希望按升序排列我的locname但是在给予时 l.LocName获取错误的顺序:ORDER BY子句在视图,内联函数,派生表,子查询中无效
答案 0 :(得分:3)
我们可以通过在视图定义中添加 TOP 100 PERCENT 子句来轻松解决问题。 尝试使用这种方式 - http://www.sqlpassion.at/archive/2015/05/25/the-ambiguity-of-the-order-by-in-sql-server/
答案 1 :(得分:2)
尝试将order by
子句迁移到最外层选择语句中 - order by
唯一有意义的地方。
像
这样的东西select LocName ,
...
from ...
order by LocName
或者,甚至更简单,将原始的复杂select
包装在外部选择中,其唯一目的是按顺序排列:
select *
from ( select
...
) t
order by t.x, t.y , ...