[英]How to create end date that is one day less than the next start date created by another another query with sql?
I queried off of a table that pulls in anyone who has working time percentage of less than 100 and all their working time records if they met the less than 100 criteria. 我查询了一个表格,该表格可以提取工作时间百分比小于100的任何人,如果他们符合少于100的条件,则提取所有工作时间记录。
This table contains the columns: id
, eff_date
(of working time percentage), and percentage
. 该表包含以下列:
id
, eff_date
(占工作时间的百分比)和percentage
。 This table does not contain end_date
. 该表不包含
end_date
。
Problem: how to build on top of the query below and add a new column called end_date
that is one date less than the next eff_date
? 问题:如何在下面的查询之上构建并添加名为
end_date
的新列,该列比下一个eff_date
少一个日期?
Current query 当前查询
select
j1.id, j1.eff_date, j1.percentage
from
working_time_table j1
where
exists (select 1
from working_time_table j2
where j2.id = j1.id and j2.percentage < 100)
Data returned from the query above: 从上面的查询返回的数据:
ID | EFF_DATE| PERCENTAGE
------------------------
12 | 01-JUN-2012 | 70
12 | 03-MAR-2013 | 100
12 | 13-DEC-2014 | 85
The desired result set is: 所需的结果集是:
ID | EFF_DATE | PERCENTAGE | END_DATE
-------------------------------------------
12 | 01-JUN-2012 | 70 | 02-MAR-2013
12 | 03-MAR-2013 | 100 | 12-DEC-2014
12 | 13-DEC-2014 | 85 | null
You didn't state your DBMS so this is ANSI SQL using window functions : 您没有声明DBMS,所以这是使用窗口函数的 ANSI SQL:
select j1.id,
j1.eff_date,
j1.percentage,
lead(j1.eff_date) over (partition by j1.id order by j1.eff_date) - interval '1' day as end_date
from working_time_table j1
where exists (select 1
from working_time_table j2
where j2.id = j1.id and j2.percentage < 100);
First off, curious if the "id" column is unique or it has duplicate values like the 12's in your sample, or is that a unique column or primary key possibly.
首先,想知道“ id”列是唯一的还是它的样本中有12个重复的值,或者是唯一列或主键。 It would be WAAAAY easier to do this if there was a unique id column that held the order.
如果有保存订单的唯一id列,这样做会很容易WAAAAY。 If you don't have a unique ID column, are you able to add one to the table?
如果您没有唯一的ID列,是否可以在表中添加一个? Again, would simplify this tremendously.
再次,将大大简化此过程。
This took forever to get right, I hope this helps, burned many hours on it. 这花了永远的时间才对,我希望这会有所帮助,并为此花费了很多时间。
Props to Akhil for helping me finally get the query right. 向Akhil提出的帮助我最终使查询正确的建议。 He is a true SQL genius.
他是一位真正的SQL天才。
Here is the .. 这里是 ..
SELECT
id,
firstTbl.eff_Date,
UPPER(DATE_FORMAT(DATE_SUB(
STR_TO_DATE(secondTbl.eff_Date, '%d-%M-%Y'),
INTERVAL 1 DAY), '%d-%b-%Y')) todate,
percentage FROM
(SELECT
(@cnt := @cnt + 1) rownum,
id, eff_date, percentage
FROM working_time_table,
(SELECT
@cnt := 0) s) firstTbl
LEFT JOIN
(SELECT
(@cnt1 := @cnt1 + 1) rownum,
eff_date
FROM working_time_table,
(SELECT
@cnt1 := 0) s) secondTbl
ON (firstTbl.rownum + 1) = secondTbl.rownum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.