我正在制作一个数据透视表,其中包含顶部的日期,旁边的客户以及中间的销售数据。作为其中的一部分,我从临时表#FileDates获取我的IN子句。以下是用于获取最旧到最新顺序的日期的代码。我想从最新到最旧的订单中获取它。
SELECT * INTO #FileDates
FROM
( SELECT distinct DLDate [DATE] from Daily where DLDate between @begin31 and @end ) TAB;
接下来是:
DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(NVARCHAR, [DATE], 106) + ']',
'[' + CONVERT(NVARCHAR, [DATE], 106) + ']')
FROM (SELECT DISTINCT [DATE] FROM #FileDates ) PV
我试图在我的子查询中放置一个order by子句但是它没有用,因为你不能在内联SQL中有顺序。我试着把它改写成:
SELECT distinct DLDate [DATE] into #FileDates
from Daily where DLDate between @begin31 and @end order by Date desc
执行命令但日期不正确。请帮忙。
答案 0 :(得分:0)
如果您有TOP,您可以使用订单。我不认为你会有1000万行。
SELECT * INTO #FileDates
FROM (
SELECT distinct TOP 999999999 DLDate [DATE]
from Daily
where DLDate between @begin31 and @end
ORDER BY DLDate DESC
) TAB;
但是,如果显式声明临时表,这就是我写它的方式。
INSERT INTO #FileDates
SELECT distinct DLDate [DATE]
from Daily
where DLDate between @begin31 and @end
ORDER BY DLDate DESC
答案 1 :(得分:0)
我接受了Ghost的建议并在出路时订购了所以我的列的选择代码现在是:
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(NVARCHAR, [DATE], 106) + ']',
'[' + CONVERT(NVARCHAR, [DATE], 106) + ']')
FROM (SELECT DISTINCT [DATE] FROM #FileDates ) PV order by [DATE] desc