簡體   English   中英

SQL按日期排序的總和

[英]SQL Sum of orders by date

我應該知道這一點,但由於某種原因,這讓我感到困惑。

這個簡單的代碼按天輸出所有訂單

USE [K.1]
Select CreatedAt,Identifier,RoundedPriceSum from StarOrder
where SiteID = 1
and OrderType <>2
and CreatedAt between '2015/01/01' and '2015/08/20'

CreatedAt是一個日期,Identifier是唯一的訂單ID,RoundedPriceSum是訂單的總數。

是否可以修改代碼以每天提供總計RoundedPriceSum_

使用GROUP BY

Select cast(CreatedAt as date) as CreatedDay, SUM(RoundedPriceSum)
from StarOrder so
where SiteID = 1 and OrderType <> 2 and
      CreatedAt >= '2015-01-01' and
      CreatedAt < '2015/08/20'
group by cast(CreatedAt as date)
order by CreatedDay;

有關查詢更改的注意事項:

  • 將日期更改為ISO標准YYYY-MM-DD格式。
  • BETWEEN替換為>=< 這樣可以更好地處理帶日期的日期。
  • 使用cast(as date)刪除時間部分。
  • 添加了ORDER BY因此結果按天排列。
select s.CreatedAt,s.Identifier,x.tot
from StarOrder s
join 
(select CreatedAt,sum(RoundedPriceSum) as tot
from StarOrder
where SiteID = 1
and OrderType <>2
and CreatedAt between '2015/01/01' and '2015/08/20'
group by createdat) x
on x.createdat = s.createdat
where SiteID = 1
and OrderType <>2
and s.CreatedAt between '2015/01/01' and '2015/08/20'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM