[英]SQL Query to group dates by month
I have a database with 3 tables: 我有一个包含3个表的数据库:
mothlist([number],[name])
temp_subs([sub_id],[date_created],[expiry_date])
temp_orders([order_id],[sub_id],[order_date])
I am trying to write a query to get the total counts expiry date and order for the current year grouped by month. 我正在尝试编写查询以获取按月分组的当前年度的总计数到期日期和顺序。
The query I have now is: 我现在的查询是:
SELECT
monthlist.name 'Month',
count(temp_subs.expiry_date) 'Expiry Date',
count(temp_orders.order_date) 'Order Date'
FROM
monthlist
FULL JOIN temp_subs
on
monthlist.number = datepart(month, temp_subs.expiry_date) and
datepart(year, temp_subs.expiry_date) = year(getdate())
FULL JOIN temp_orders
on
monthlist.number = datepart(month, temp_orders.order_date) and
datepart(year, temp_orders.order_date) = year(getdate())
GROUP BY monthlist.number ,monthlist.name
ORDER BY monthlist.number
If someone could tell me what am I dong wrong here I would be very grateful. 如果有人能告诉我我在哪里错了,我将不胜感激。
A double join means that every temp_sub is repeat for every temp_order. 双重联接意味着每个temp_sub对每个temp_order重复。 One way to avoid double-counting is adding a distinct
on a unique column. 为了避免重复计算的一种方法是增加一个distinct
的唯一列。 If the tables have a primary key called id
, that could look like: 如果表具有一个名为id
的主键,则它可能类似于:
SELECT monthlist.name 'Month'
,count(distinct temp_subs.id) 'Expiry Date'
,count(distinct temp_orders.id) 'Order Date'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.