简体   繁体   English

SQL:一个月内的总天数

[英]SQL: Total days in a month

I have the following formula: 我有以下公式:

"Value1" * 100 * "Total day in a month" * "Value2"

I have the following table: 我有下表:

ID     Date        Time     Value1     Value2
1      2014-01-01  00:00    10         20
2      2014-01-01  01:00    20         5

I want to select a data in a year with only using one parameter which is Year . 我想在一年中选择一个数据,只使用一个参数,即Year
How can I apply the formula into a query? 如何将公式应用于查询?

The result should be: 结果应该是:

ID     Date        Time     Value1     Value2   TotalDayinMonth   Result
1      2014-01-01  00:00    10         20       31                620000
2      2014-01-01  01:00    20         5        31                310000
ff.   

You can get the number of days of a given date like this: 您可以像这样获得给定日期的天数:

DECLARE @date DATETIME = '2014-01-01'
SELECT DATEDIFF(DAY, @date, DATEADD(MONTH, 1, @date))

And the query: 和查询:

SELECT  ID
        ,[Date]
        ,[Time]
        ,Value1
        ,Value2
        ,DATEDIFF(DAY, [Date], DATEADD(MONTH, 1, [Date])) AS TotalDayinMonth
        ,Value1 * 100 * DATEDIFF(DAY, [Date], DATEADD(MONTH, 1, [Date])) * Value2 AS Result
FROM yourTable

This expression will give you the number of days in the month that date is in no matter what day it is: 此表达式将为您提供该date所在月份的天数,无论它是在哪一天:

datediff(day,
  dateadd(month,datediff(month, 0, date),0),
  dateadd(month,datediff(month, 0, date)+1,0))

Check this answer. 检查这个答案。 You can use EOMONTH AND DAY function of SQL to get number of days in a month. 您可以使用SQL的EOMONTH AND DAY函数来获取一个月内的天数。

SELECT  ID
        ,[Date]
        ,[Time]
        ,Value1
        ,Value2
        ,DAY(EOMONTH(Date)) AS TotalDaysInMonth
        ,Value1 * 100 * DAY(EOMONTH(Date)) * Value2 AS Result
FROM TABLENAME

you can check this also. 你也可以检查一下。

declare @t table (ID  int, Date date, Time time, Value1 int, Value2 int)

insert into @t values (1,'2014-01-01','00:00',10,20 ) ,  (2,'2014-01-01','00:00',20,5 ),  (3,'2014-02-01','00:00',20,5 )

select * from @t

; with cte as
(
    select id,
        day(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,DATE)+1,0))) Totaldayofmonth      
    from @t
)
--select * from cte
select 
    *, Value1 * 100 * Totaldayofmonth * Value2
from 
    @t t inner join cte on cte.ID = t.id

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

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