我正在尝试修改当前查询以返回每年每个月的第一笔订单。
这是我的完整表格和当前查询。
select orderdate, sum(UnitPrice*Qty)
AS month_firstOrder_total
from OrderByDate
group by OrderDate
答案 0 :(得分:1)
尝试这样的事情:
WITH DataSource AS
(
select *
,ROW_NUMBER() OVER (PARTITION BY YEAR(orderdate), MONTH(orderdate) ORDER BY orderdate ASC) rn
from OrderByDate
)
SELECT *
FROM DataSource
WHERE rn = 1;
如果需要,您还可以获取每个订单日期的总金额:
WITH DataSource AS
(
select *
,ROW_NUMBER() OVER (PARTITION BY YEAR(orderdate), MONTH(orderdate) ORDER BY orderdate ASC) rn
,sum(UnitPrice*Qty) OVER (PARTITION BY orderdate) as sum_qty
from OrderByDate
)
SELECT *
FROM DataSource
WHERE rn = 1
答案 1 :(得分:0)
您可以创建一个MONTH列吗?
然后选择Min(id)并按MONTH排序。
我只是猜测
select *
from
(select min(id), month, sum(UnitPrice * Qty)
from your_table_name
group by month)