来自GROUP BY JOIN的SUM总数的最大值

时间:2018-10-10 12:36:54

标签: sql sql-server tsql

我被困住了。

我有两个表:

首先,[PurchasedItemsByCustomer]的列:

[CustID] INT NULL,
[ItemId] INT NULL,
[Quantity] INT NULL,
[OnDate] DATE NULL

第二,表[Items]中的列:

[ItemId] INT NULL,
[Price] FLOAT NULL,
[CategoryId] INT NULL

我需要输出3列的列表:

  • 一个月
  • 该月(商品数量)中销量最高的类别
  • 该月购买了该类别的商品有多少。

谢谢

3 个答案:

答案 0 :(得分:0)

我认为您可以使用这样的查询:

;With SoldPerMonth as (
    select datepart(month, p.onDate) [Month], i.CategoryId [Category], sum(p.Quntity) [Count]
    from PurchasedItemsByCustomer p
    join Items i on p.ItemId = i.ItemId
    group by datepart(month, p.onDate), i.CategoryId
), SoldPerMonthRanked as (
    select *, rank() over (partition by [Month] order by [Count] desc) rnk
    from SoldPerMonth
)
select [Month], [Category], [Count]
from SoldPerMonthRanked
where rnk = 1;

SQL Server Demo

  

注意:在上述查询中,如果您只想返回一行,请使用rank()来使用row_number()

答案 1 :(得分:0)

您在这里,

input

答案 2 :(得分:0)

Divide et Impera:

with dept_sales as(
select month(ondate) as month, year(ondate) as year, category, count(*) as N -- measure sales for each month and category
from purchase join items using itemid
group by year(ondate), month(ondate), category)

select top 1 * --pick the highest
from dept_sales
where year = year(current_timestamp) -- I imagine you need data only for current year
order by N desc --order by N asc if you want the least selling category

如果不按年份分组,则将在同一“一月”项中获得所有年份的一月,因此我在当年添加了一个过滤器。

我使用CTE来简化代码,以分隔计算阶段,如果需要,可以嵌套它们。