每月退回第一笔订单

时间:2018-08-21 04:38:29

标签: sql sql-server tsql

我正在尝试修改当前查询以返回每年每个月的第一笔订单。

这是我的完整表格和当前查询。

select orderdate, sum(UnitPrice*Qty) 
AS month_firstOrder_total
from OrderByDate
group by OrderDate

enter image description here

2 个答案:

答案 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)