TABLE有四個欄位 "商品代碼","個數", "金額","販售日期"
商品代碼有四種以上,
販售日期有相同天與不同天
※需要呈現的結果:
(1) 銷售日期的時間需要去掉,只保留年月日,像是"2015/01/13"
(2) 商品代碼相同且需要同一天才可以將數量與金額總和
(3) 可以考慮到多個商品代碼
我的測試檔案https://drive.google.com/file/d/1j7lskVBtk8sO2nGTWhchBTCm65ZPGw2H/view?usp=sharing
提供的內容:
目前我的語法會出現無法相同1天合併,以及無法將同1天的數量和金額都加總,
提供我目前寫的語法:
select
COM_D2.商品代碼,
sum(COM_D2.個數) as 每日單件商品數量總和,
sum(COM_D2.金額) as 每日單件商品金額總和,
convert(varchar(10), convert(datetime, COM_D2.販售日期, 111), 111) as 日期
from COM_D2
group by COM.D2, COM_D2.販售日期
order by COM.D2, COM_D2.販售日期
真正需要的結果:
請問如何改善查詢結果的方式
謝謝
如果妳的COM_D2.販售日期
欄位是datetime
型別,可以嘗試使用CAST
來轉換成datetime
.
另外再gorup by
也是使用CAST(COM_D2.販售日期 AS DATE)
而不是COM_D2.販售日期
,因為你group by COM_D2.販售日期
的分組會包含 時:分:秒
select
COM_D2.商品代碼,
sum(COM_D2.個數) as 每日單件商品數量總和,
sum(COM_D2.金額) as 每日單件商品金額總和,
CAST(COM_D2.販售日期 AS DATE) as 日期
from COM_D2
group by COM.D2, CAST(COM_D2.販售日期 AS DATE)
order by COM.D2, CAST(COM_D2.販售日期 AS DATE)
Group by COM_D2.販售日期時,沒有先convert成 yyyy/mm/dd,
就會連同時分秒一起Group by,所以沒有辦法取回你想要的
select
COM_D2.商品代碼,
sum(COM_D2.個數) as 每日單件商品數量總和,
sum(COM_D2.金額) as 每日單件商品金額總和,
convert(varchar(10), convert(datetime, COM_D2.販售日期), 111) as 日期
from COM_D2
group by COM.D2, convert(varchar(10), convert(datetime, COM_D2.販售日期), 111)
order by COM.D2, convert(varchar(10), convert(datetime, COM_D2.販售日期), 111)
select a1 as '商品代碼',sum(a2) as '個數' ,sum(a3) as '金額',
CONVERT(varchar(12), convert(date,a4), 111) as '銷售日期'
from COM_D2
where 1=1
group by a1,CONVERT(varchar(12), convert(date,a4), 111)
order by a1,CONVERT(varchar(12), convert(date,a4), 111)
Demo :
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=90e61696a395afd85f5b435b6c249b2a
select t.商品代碼, sum(t.每日單件商品數量總和), sum(t.每日單件商品金額總和), t.日期 from
(
select
COM_D2.商品代碼,
COM_D2.個數 as 每日單件商品數量總和,
COM_D2.金額 as 每日單件商品金額總和,
convert(varchar(10), convert(datetime, COM_D2.販售日期, 111), 102) as 日期
from COM_D2
) t
group by t.日期, t.商品代碼
order by t.日期 asc