在#temp表格中,我的值为
Month Sales
JUN 2015 600.00
JAN 2015 5000.00
MAR 2015 3500.00
MAY 2015 1000.00
FEB 2015 1500.00
APR 2015 1400.00
如何按月更新#temp表并按修改后的更改更改表,我使用了order by DATEPART(mm,CAST( Substring( Month, 1, CharIndex( ' ', Month ) - 1)+ ' 1900' AS DATETIME)) asc
但是在#temp
预期产出:
Month Sales
JAN 2015 5000.00
FEB 2015 1500.00
MAR 2015 3500.00
APR 2015 1400.00
MAY 2015 1000.00
JUN 2015 600.00
所以下次如果我select * from #temp
,我应该得到预期的输出
答案 0 :(得分:3)
试试这个:
只需 CAST(MonthVal AS DATE)
DECLARE @Table TABLE
(MonthVal VARCHAR(10), Sales DECIMAL(8,2))
INSERT INTO @Table
VALUES
('JUN 2015', 600.00 ),
('JAN 2015', 5000.00),
('MAR 2015', 3500.00),
('MAY 2015', 1000.00),
('FEB 2015', 1500.00),
('APR 2015', 1400.00)
SELECT
*
FROM
@Table
ORDER BY
CAST(MonthVal AS DATE)
答案 1 :(得分:1)
使临时表具有一个额外的整数,自动递增(identity
)主键列。现在,当您按特定顺序插入该表时,将保留此订单。
修改强>
由于订单只能在汇总临时表的内容后计算,因此引入额外的整数列(id
) - 而不是标识列 - 可能有所帮助。这应该通过合适的update
语句设置为月份的数字等效,然后可以用于对临时表的内容进行排序。请参阅此处以获取一些示例:http://data.stackexchange.com/stackoverflow/query/336013/default-order-of-temp-table?opt.textResults=true
但无论如何,必须始终使用order by id
子句。
答案 2 :(得分:0)
declare @t table (Month varchar(10),sales decimal(18,2))
insert into @t (Month,sales)values ('JUN 2015',600.00),
('JAN 2015', 5000.00 ),
('MAR 2015',3500.00 ),
('MAY 2015',1000.00 )
select MONTH,sales from @t order by DATEPART(MM,month)