[英]Function that will select value from SQL table and do a sum based on another column value
I need a query to sum up the hours
in a table.我需要一个查询来总结表中的hours
。 Which hours need to be selected depends on the Start Date
column.需要选择哪些时间取决于Start Date
列。 If the start date is in the past, then it should take Remaining Hours
, if it's in the future it should take Budgeted Hours
.如果开始日期是过去的,则应采用Remaining Hours
,如果是未来的日期,则应采用Budgeted Hours
。
Start Date开始日期 | Budgeted Hours预算时间 | Remaining Hours剩余时间 |
---|---|---|
Jan 1, 2022 2022 年 1 月 1 日 | 15 15 | 3 3个 |
Feb 1, 2022 2022 年 2 月 1 日 | 12 12 | 0 0 |
Mar 1, 2022 2022 年 3 月 1 日 | 14 14 | 6 6个 |
Apr 1, 2022 2022 年 4 月 1 日 | 15 15 | 13 13 |
In the example above the summed up hours should be 24 (3 + 0 + 6 + 15).在上面的示例中,总小时数应为 24 (3 + 0 + 6 + 15)。
You don't need a function for this, just a CASE
expression:为此,您不需要 function,只需要一个CASE
表达式:
DECLARE @now datetime = GETDATE();
SELECT SUM
(
CASE WHEN [Start Date] < @now
THEN [Remaining Hours]
ELSE [Budgeted Hours]
END
)
FROM dbo.tablename;
We can use the function case
我们可以使用 function case
create table ops( startDate date, Budgeted int, Remaining int);
insert into ops values ('2022-01-01',15,3), ('2022-02-01',12,0), ('2022-03-01',14,6), ('2022-04-01',15,13), ('2022-05-01',10,18);
select startDate, Budgeted, Remaining, case when startDate < getDate() then Remaining else Budgeted end Hours from ops;
startDate |开始日期 | Budgeted |预算 | Remaining |剩余 | Hours:--------- |营业时间:-------- | -------: | ------: | --------: | ------: | ----: 2022-01-01 | ----: 2022-01-01 | 15 | 15 | 3 | 3 | 3 2022-02-01 | 3 2022-02-01 | 12 | 12 | 0 | 0 | 0 2022-03-01 | 0 2022-03-01 | 14 | 14 | 6 | 6 | 6 2022-04-01 | 6 2022-04-01 | 15 | 15 | 13 | 13 | 15 2022-05-01 | 15 2022-05-01 | 10 | 10 | 18 | 18 | 10 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.