简体   繁体   English

SQL查询按月分组日期

[英]SQL Query to group dates by month

I have a database with 3 tables: 我有一个包含3个表的数据库:

  1. mothlist([number],[name])
  2. temp_subs([sub_id],[date_created],[expiry_date])
  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM