可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
like the title said, here is my code:
SELECT
material,
SUM([Amount]) AS [Amount],
RIGHT(CONVERT(varchar(50), [date_in], 106), 8)
FROM
[rec_stats]
GROUP BY
material,
RIGHT(CONVERT(varchar(50), [date_in], 106), 8)
ORDER BY
material,date_in
the code wont run because of the date_in, is there anyway to get around this?
回答1:
Apply another aggregate, so how about;
order by min([date_in])
回答2:
Order by the same expression you're grouping by.
It is better to group and order on the DATE
representation of the month.
In SQL Server 2008
that would be:
SELECT material, SUM([Amount]) AS [Amount], DATEADD(d, 1 - DAY(GETDATE()), CAST(GETDATE() AS DATE))
FROM [rec_stats]
GROUP BY
material,
DATEADD(d, 1 - DAY(GETDATE()), CAST(GETDATE() AS DATE))
ORDER BY
material, DATEADD(d, 1 - DAY(GETDATE()), CAST(GETDATE() AS DATE))
回答3:
You can only order by what is possible to use in a select statement. Date_in by itself is not possible in the selection statement so you can't use it. Depending on your RDBMS you can do the following:
SELECT
material,
SUM([Amount]) AS [Amount],
RIGHT(CONVERT(varchar(50), [date_in], 106), 8)
FROM
[rec_stats]
GROUP BY
material,
RIGHT(CONVERT(varchar(50), [date_in], 106), 8)
ORDER BY
material,RIGHT(CONVERT(varchar(50), [date_in], 106), 8)
回答4:
Are you trying to aggregate by month? If so, try:
SELECT
material,
SUM([Amount]) AS [Amount],
DATEPART(year, [date_in]) as y,
DATEPART(month, [date_in]) as m,
DATEPART(month, [date_in]) + ' ' + DATEPART(year, [date_in]) AS MonthYearCombined
FROM
[rec_stats]
GROUP BY
material,
DATEPART(year, [date_in]),
DATEPART(month, [date_in])
ORDER BY
material,y,m
Note: You may have to convert the values in the "MonthYearCombined" column - I would actually recommend you do that in code rather than SQL, but wanted to include some reference to it.
回答5:
You cannot deal with the date_in column like your original query. Rather, you can NEST the query and read it like this:
SELECT
material,
SUM([Amount]) AS [Amount],
RIGHT(CONVERT(varchar(50), [date_in], 106), 8)
FROM
(
Select material, Amount, RIGHT(CONVERT(varchar(50), [date_in], 106), 8) as DateIn
From [rec_stats]
) X
GROUP BY
material,
DateIn
ORDER BY
material,DateIn
I cannot test it in my dev environment but I believe this gives you the idea.
回答6:
use this
order by
1,2,3,4,5