整个数据集的不同计数,按月分组

时间:2018-12-19 20:18:27

标签: sql sql-server sql-server-2012 count distinct

我正在处理一个看起来像这样的销售订单表(ORDER)(已更新2018/12/20以更接近我的实际数据集):

SOID         SOLINEID         INVOICEDATE         SALESAMOUNT     AC
5            1                2018-11-30          100.00          01
5            2                2018-12-05          50.00           02
4            1                2018-12-12          25.00           17
3            1                2017-12-31          75.00           03
3            2                2018-01-03          25.00           05
2            1                2017-11-25          100.00          17
2            2                2017-11-27          35.00           03
1            1                2017-11-20          15.00           08
1            2                2018-03-15          30.00           17
1            3                2018-04-03          200.00          05

我能够通过SOID和SOLINEID计算平均销售额:

SELECT SUM(SALESAMOUNT) / COUNT(DISTINCT SOID) AS 'Total Sales per Order ($)',
    SUM(SALESAMOUNT) / COUNT(SOLINEID) AS 'Total Sales per Line ($)'
FROM ORDER

这似乎提供了一个很好的答案,但随后又给了我一个额外的约束,即按年和月进行此计数。我以为我可以简单地添加

GROUP BY YEAR(INVOICEDATE), MONTH(MONTH)

但是这会聚集SOID,然后执行COUNT(DISTINCT SOID)。这会导致SOID出现问题,这种问题会持续多个月出现,这很常见,因为我们在发货时开具发票。

我想得到这样的东西:

Year     Month     Total Sales Per Order    Total Sales Per Line
2018     11        0.00                     

一个非常棘手的问题是,我需要一种方法来定义SOID跨多个月份和年份进行汇总;为此,我将使用MAX(INVOICEDATE)。

但是,我不确定从那里如何解决这个问题。与?子查询?还有吗我将不胜感激,即使它指向正确的方向。

2 个答案:

答案 0 :(得分:1)

您应该选择Year()和month()进行发起和分组依据

SELECT YEAR(INVOICEDATE) year
  , MONTH(INVOICEDATE) month
  , SUM(SALESAMOUNT) / COUNT(DISTINCT SOID) AS 'Total Sales per Order ($)'
  , SUM(SALESAMOUNT) / COUNT(SOLINEID) AS 'Total Sales per Line ($)'
FROM ORDER
GROUP BY YEAR(INVOICEDATE), MONTH(INVOICEDATE)

答案 1 :(得分:0)

以下是结果,但数据示例没有enuf行显示月份...

SELECT
    mDateYYYY,
    mDateMM,
    SUM(SALESAMOUNT) / COUNT(DISTINCT t1.SOID) AS 'Total Sales per Order ($)',
    SUM(SALESAMOUNT) / COUNT(SOLINEID) AS 'Total Sales per Line ($)'
FROM DCORDER as t1
left join
    (Select
     SOID
     ,Year(max(INVOICEDATE)) as mDateYYYY
     ,Month(max(INVOICEDATE)) as mDateMM
From DCOrder 
Group By SOID
     ) as t2
 On t1.SOID = t2.SOID

 Group by mDateYYYY, mDateMM

mDateYYYY   mDateMM Total Sales per Order ($)   Total Sales per Line ($)
2018        12      87.50                       58.33

我使用了新的SQL仍然是MAX(INVOICEDATE)(不超过上面),带有新的12/20数据,并且排除了AC = 17。

YYYY    MM  Total Sales per Order ($)   Total Sales per Line ($)
2017    11   35.00                       35.00
2018     1  100.00                       50.00
2018     4  215.00                      107.50
2018    12  150.00                       75.00