T-SQL。 GroupBy截断DATETIME并按顺序排序

问题描述 投票:0回答:3

我有一个简单的订单表,如:

Order
=========
Date (DATETIME)
Price (INT) 

我想知道我们每个月赚多少钱,输出应该是这样的:

January-2018 : 100 
February-2018: 200
...
January-2019: 300
...

我有以下SQL:

SELECT 
    DATENAME(MONTH , DATEADD(M, t.MDate , -1 ) ) + '-' + CAST(t.YDate as NVARCHAR(20)),
    SUM(Price)
FROM 
(
SELECT 
    DATEPART(YYYY, o.Date) as YDate,
    DATEPART(MM, o.Date) as MDate,  
    Price
FROM [Order] o
) t
GROUP BY t.YDate, t.MDate
ORDER BY t.YDate, t.MDate

可以,还是有更好的方法?

sql sql-server tsql
3个回答
0
投票

format()是要走的路。我建议:

select format(o.date, 'MMMM-yyyy') as Monthyear,    
       sum(o.price) as total 
from orders o
group by format(datenew, 'MMMM-yyyy')
order by min(o.date)

0
投票

如果您使用的是Sql server 2012或+,您也可以使用格式化功能。

select cast('2018-02-23 15:34:09.390' as datetime)  as datenew, 100 as price  into #temp union all 
select cast('2018-02-24 15:34:09.390' as datetime)  as datenew, 300 as price   union all 
select cast('2018-03-10 15:34:09.390' as datetime)  as datenew, 500 as price   union all 
select cast('2018-03-11 15:34:09.390' as datetime)  as datenew, 700 as price   union all 
select cast('2019-02-23 15:34:09.390' as datetime)  as datenew, 900 as price   union all 
select cast('2019-02-23 15:34:09.390' as datetime)  as datenew,  1500 as price    

select Monthyear,  total  from  ( 
select format(datenew, 'MMMM-yyyy') Monthyear, format(datenew, 'yyyyMM')  NumMMYY ,sum(price) total from #temp 
group by format(datenew, 'MMMM-yyyy') , format(datenew, 'yyyyMM') ) test 
order by NumMMYY

由于format会将其转换为nvarchar,因此我必须在子查询中再创建一个列来正确排序。如果您不介意再使用一个列,则不必使用子查询,并且可以使用其他列进行排序。我找不到任何其他方式(除了案例陈述,这不是一个非常好的主意)在同一个选择中做到这一点

Output: 
 Monthyear      Total
 February-2018  400
 March-2018     1200
 February-2019  2400

0
投票

也许只是这个?

with Orders as (
  select convert(date,'2018-01-15') as [date], 10 as Price union all
  select convert(date,'2018-01-20'), 20 union all
  select convert(date,'2018-01-30'), 30 union all
  select convert(date,'2018-02-15'), 20 union all
  select convert(date,'2018-03-15'), 40 union all
  select convert(date,'2018-03-20'), 50

)
select 
  datename(month,o.Date) + '-' + datename(year,o.Date) + ': ' + 
  convert(varchar(max),SUM(Price))
FROM [Orders] o
group by datename(month,o.Date) + '-' + datename(year,o.Date)
order by 1 desc

我不清楚为什么你在查询中删除一个月,我不是这样做的。你可以在这里测试一下:https://rextester.com/GRKK80105

© www.soinside.com 2019 - 2024. All rights reserved.