is it possible to use ORDER BY column not in the GROUP BY?

拟墨画扇 提交于 2019-12-08 17:45:13

问题


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:


use this

order by
1,2,3,4,5



回答4:


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)



回答5:


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.




回答6:


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.



来源:https://stackoverflow.com/questions/5818216/is-it-possible-to-use-order-by-column-not-in-the-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!