在两个日期之间求和()值的最佳方法(第二个日期存储为下一行中的值)-postgres
Best way to sum() values between two dates (where the second date is stored as a value in the next row) - postgres
我对 psql 查询遇到的问题有点困惑。我知道我将如何使用循环等来解决这个问题,但由于我不是专家,所以在 SQL 中遇到了困难。
如果我们假设每个学年有3个学期。每个 child 每个月都可以获得午餐津贴。我想 SUM() 每个月的津贴,从学期开始到下学期。
我卡住的地方是下一个学期的日期是 terms
table.
中下一行数据中的一个值
我有这样的东西:
SELECT
terms."startDate",
COALESCE((
SELECT
SUM("lunch")
FROM
"allowance"
WHERE
TO_CHAR(terms."startDate", 'YYYY-MM') >= TO_CHAR("date", 'YYYY-MM')
AND
TO_CHAR(terms."startDate", 'YYYY-MM') < TO_CHAR(??? HELP ???, 'YYYY-MM')
),0) AS "lunchMoney"
FROM "schoolTerms" AS terms
...
我放 TO_CHAR(??? HELP ???, 'YYYY-MM')
的地方我想参考 child 下学期的开始日期。我研究过使用 LEAD()
方法,但无法弄清楚。
如有任何帮助,我们将不胜感激。
我想你想要加入和聚合:
select t.startdate, t.enddate, sum(a.lunch) as lunch_money
from schoolterms t
inner join allowance a on a.date >= t.startdate and a.date < t.enddate
group by t.startdate, t.enddate
这会将每个津贴放入其所属的术语中,然后按术语汇总。如果可能有没有任何津贴的条款,您可能想要 left join
。
您当前的查询没有提供有关“child”是什么的任何线索。据推测,这应该是 allowance
中的一列,您可能希望将其放入 select
和 group by
子句中。
如果要将 end_date
计算为“下一个”start_date
,则使用 lead()
:
select t.startdate, t.enddate, sum(a.lunch) as lunch_money
from (
select start_date,
lead(startdate) over(order by startdate) enddate
from schoolterms
) t
inner join allowance a
on a.date >= t.startdate
and (a.date < t.enddate or t.enddate is null)
group by t.startdate, t.enddate
我对 psql 查询遇到的问题有点困惑。我知道我将如何使用循环等来解决这个问题,但由于我不是专家,所以在 SQL 中遇到了困难。
如果我们假设每个学年有3个学期。每个 child 每个月都可以获得午餐津贴。我想 SUM() 每个月的津贴,从学期开始到下学期。
我卡住的地方是下一个学期的日期是 terms
table.
我有这样的东西:
SELECT
terms."startDate",
COALESCE((
SELECT
SUM("lunch")
FROM
"allowance"
WHERE
TO_CHAR(terms."startDate", 'YYYY-MM') >= TO_CHAR("date", 'YYYY-MM')
AND
TO_CHAR(terms."startDate", 'YYYY-MM') < TO_CHAR(??? HELP ???, 'YYYY-MM')
),0) AS "lunchMoney"
FROM "schoolTerms" AS terms
...
我放 TO_CHAR(??? HELP ???, 'YYYY-MM')
的地方我想参考 child 下学期的开始日期。我研究过使用 LEAD()
方法,但无法弄清楚。
如有任何帮助,我们将不胜感激。
我想你想要加入和聚合:
select t.startdate, t.enddate, sum(a.lunch) as lunch_money
from schoolterms t
inner join allowance a on a.date >= t.startdate and a.date < t.enddate
group by t.startdate, t.enddate
这会将每个津贴放入其所属的术语中,然后按术语汇总。如果可能有没有任何津贴的条款,您可能想要 left join
。
您当前的查询没有提供有关“child”是什么的任何线索。据推测,这应该是 allowance
中的一列,您可能希望将其放入 select
和 group by
子句中。
如果要将 end_date
计算为“下一个”start_date
,则使用 lead()
:
select t.startdate, t.enddate, sum(a.lunch) as lunch_money
from (
select start_date,
lead(startdate) over(order by startdate) enddate
from schoolterms
) t
inner join allowance a
on a.date >= t.startdate
and (a.date < t.enddate or t.enddate is null)
group by t.startdate, t.enddate