简体   繁体   English

SQL每月平均总天数

[英]SQL Average of total days in DATA per month

I have a SQL question. 我有一个SQL问题。 I am trying to find the average injection volume per month. 我正在尝试查找每月的平均注射量。 Currently my code takes the sum of all days of injection, and divides them by the TOTAL DAYS in the month . 目前,我的代码将所有注入天数的总和除以该月TOTAL DAYS天

Sum(W1."INJECTION_VOLUME" /
EXTRACT(DAY FROM LAST_DAY(W1."INJECTION_DATE"))) AS "AVGINJ"

This is not what I wanted. 这不是我想要的。 I need to take the injection_volume and divide by the total days in the DATA . 我需要把injection_volume除以DATA中的总天数。

ie. 即。 right now the data only 8 days of injection volume , lets say it is 3000. 现在的数据只有injection volume 8天,可以说是3000。

So right now the sql is 3000/31. 所以现在的SQL是3000/31。

I need to have it be 3000/8 (the total days in the data for the current month.) 我需要将其设置为3000/8(本月数据中的总天数。)

Also, this should only be for the current month. 此外,这仅适用于当前月份。 All other completed months should be divided by the total days in the month. 所有其他完成的月份应除以该月份的总天数。

In order to get the average of the data for the current month you will need to divide by the count in the month: 为了获得当月数据的平均值,您需要除以该月的计数:

SUM(`W1`.`INJECTION_VOLUME` / COUNT(EXTRACT(YEAR_MONTH FROM `W1`.`INJECTION_DATE`)))

To get all other data as the full month you'll need to combine your code: 要获得一个月的所有其他数据,您需要合并代码:

SUM(`W1`.`INJECTION_VOLUME` / EXTRACT(DAY FROM LAST_DAY(`W1`.`INJECTION_DATE`)))

With an IF . IF So something like this: 所以像这样:

SUM(
    IF(
        EXTRACT(YEAR_MONTH FROM `W1`.`INJECTION_DATE`) = EXTRACT(YEAR_MONTH FROM NOW()), 
        `W1`.`INJECTION_VOLUME` / COUNT(EXTRACT(YEAR_MONTH FROM `W1`.`INJECTION_DATE`)), 
        `W1`.`INJECTION_VOLUME` / EXTRACT(DAY FROM LAST_DAY(`W1`.`INJECTION_DATE`)
    )
)

Note: this is untested and I'm not sure about the RDBMS you are using so you may need to change the code slightly to make it work. 注意:这未经测试,我不确定您使用的RDBMS是什么,因此您可能需要稍微更改代码才能使其正常工作。

Use 采用

SELECT
SUM(W1.INJECTION_VOLUME) / COUNT(DISTINCT MyDateField)
FROM MyTable
WHERE X=Value

This gives you what you're after 这给你你所追求的

SUM(W1.INJECTION_VOLUME) is the total volume for the dataset

Gives you the number of days, no matter how many records you have 无论您有多少条记录,都可以为您提供天数

COUNT(DISTINCT MyDateField)

So if you have 100 records but only 5 actual unique days in this time, this expression gives you 5 因此,如果您这次有100条记录,但实际只有5天不重复,那么此表达式将为您提供5

Note that this kind of calc is normally worked out with 注意,这种计算通常是用

SUM(A) / SUM(B)

not

SUM(A/B)

They give you completely different answers. 他们给您完全不同的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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