2017-04-05 140 views
0
select max(total), date 
from (select sum(total) as total, date as date 
     from canteen 
     group by date) as max 

我想購買的出售最高和從表中最高銷售日期。從sql表中選擇銷售額最高的日期

我的查詢顯示此錯誤。

異常,錯誤代碼8120和SQLState S0001]柱「max.date」是 在選擇列表中無效的,因爲它不是在任一種 聚合函數或GROUP BY子句含有。

回答

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 
+0

非常感謝。有效 。如果沒有太多的麻煩,你可以告訴我我的查詢有什麼問題 –

+0

@Mohit:你忘記了通過&order by添加group到你的外部查詢。 – samithagun

+0

@Mohit:你已經在外部查詢中使用了select max(total) –

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 
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 
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 
相關問題