每月,每年和货币的总折扣,不包括2017年的数据

时间:2019-05-27 10:19:11

标签: sql sql-server

我需要知道每月,每年和所用货币的总折扣,不包括该数据库的2017年数据:

Sales table:
PK sale_id : text
FK1 client_id : text
tax_code : text
currency : text
amount : integer
notes : text
created_at : timestamp

Sales_entries table:
PK sale_entry_id : text
FK1 sale_id : text
price : integer
discount : integer
FK2 journey_id : text

我创建了此查询,但是我不知道它是否正确:

Select
Datetrunc(‘month’, a.created_at) as month,
Datetrunc(‘year’, a.created_at) as year,
a.Currency as currency,
Sum(b.discount) as discount
From sales as a
Left join sales_entries as b 
On a.sales_id = b.sale_id
Where year <> 2017
Group by
Month,
Year,
currency

1 个答案:

答案 0 :(得分:1)

您的日期算术有点差。我想这就是你想要的:

select year(s.created_at) as yyyy,
       month(s.created_at) as mm,
       s.Currency as currency,
       sum(se.discount) as discount
from sales s left join
     sales_entries se
     on s.sales_id = se.sale_id
where s.created_at < '2017-01-01' or
      s.created_at >= '2018-01-01'
group by year(s.created_at), month(s.created_at),
         s.currency
order by year(s.created_at), month(s.created_at), s.currency;

请注意,我还将表别名替换为有意义的缩写,而不是任意字母。