like the title said, here is my code:
S开发者_运维百科ELECT
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?
Apply another aggregate, so how about;
order by min([date_in])
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))
use this
order by 1,2,3,4,5
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)
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.
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.
精彩评论