select max(total), date
from (select sum(total) as total, date as date
from canteen
group by date) as max
我想从表中选择最高销售额和最高销售日期。
使用我的查询显示此错误。
异常,错误代码8,120,SQLState S0001]列' max.date'是 在选择列表中无效,因为它不包含在任何一个中 聚合函数或GROUP BY子句。
答案 0 :(得分:1)
您可以使用order by,将您的数据设置为按销售顺序降序并获取第一行。
如果您想按日期结果,那么您可以使用ROW_NUMBER()
select TOP(1) total, date
from
(
select sum(total) as total, date as date
from canteen
group by date
) as max
Order by todal desc
答案 1 :(得分:0)
这将返回达到最大销售总额的所有日期。 Here是一个演示。
; with x as (
select sum(total) as total, date from canteen group by date
)
, y as (
select dr = dense_rank() over(order by total desc), *
from x
)
select * from y where dr = 1
答案 2 :(得分:0)
如果你想得到所有日期的最大值(总数),这里就是
;with temp as
(
select sum(total) as total, date as date
from canteen
group by date
)
SELECT TOP 1 WITH TIES *
FROM temp
ORDER BY temp.total desc
答案 3 :(得分:0)
您忘记添加分组&在您的外部查询中排序。我已修改它以按降序显示所有销售。所以最高的销售将是最重要的。
select max(total) total, date
from (select sum(total) as total, date as date
from canteen
group by date) as max
group by date
order by total desc