Getting latest value from joined table - sql-server

I have 2 tables joined by a mapping table
I want to get the the intensity from the last Tap.
With IssuesCTE AS
(
Select * from Issues
),
TapsCTE AS
(
SELECT
MapIssueTaps.IssueId,
SD.Id,
SD.Intensity,
SD.Notes,
Row_Number() OVER
(
PARTITION BY MapIssueTaps.IssueId ORDER BY SD.CreatedOn DESC) AS RowNumber
FROM Taps SD
join MapIssueTaps on MapIssueTaps.TapId=SD.Id
)
Select IssuesCTE.*,TapsCTE.* from IssuesCTE,TapsCTE
join MapIssueTaps on MapIssueTaps.TapId = TapsCTE.Id
--where RowNumber=1
Here is all the data:
UserId Id Name Intensity CreatedOn UpdatedOn Description IssueId Id Intensity Notes RowNumber
A291B6F4-866D-4EFA-9522-7AA45710C7E0 1 c 2 2014-02-02 03:53:33.200 2014-02-02 03:53:33.200 cx 1 3 8 dd 1
A291B6F4-866D-4EFA-9522-7AA45710C7E0 8 d 5 2014-02-03 22:16:24.157 2014-02-03 22:16:24.157 d 1 3 8 dd 1
A291B6F4-866D-4EFA-9522-7AA45710C7E0 1 c 2 2014-02-02 03:53:33.200 2014-02-02 03:53:33.200 cx 1 2 1 xzc 2
A291B6F4-866D-4EFA-9522-7AA45710C7E0 8 d 5 2014-02-03 22:16:24.157 2014-02-03 22:16:24.157 d 1 2 1 xzc 2
A291B6F4-866D-4EFA-9522-7AA45710C7E0 1 c 2 2014-02-02 03:53:33.200 2014-02-02 03:53:33.200 cx 1 1 8 ss 3
A291B6F4-866D-4EFA-9522-7AA45710C7E0 8 d 5 2014-02-03 22:16:24.157 2014-02-03 22:16:24.157 d 1 1 8 ss 3
I would like this:
UserId Id Name Intensity CreatedOn UpdatedOn Description IssueId Id Intensity Notes RowNumber
A291B6F4-866D-4EFA-9522-7AA45710C7E0 1 c 2 2014-02-02 03:53:33.200 2014-02-02 03:53:33.200 cx 1 3 8 dd 1
A291B6F4-866D-4EFA-9522-7AA45710C7E0 8 d 5 2014-02-03 22:16:24.157 2014-02-03 22:16:24.157 d 1 3 null dd 1
How can I do it?

Related

Dynamically find unpaid invoices

How can I dynamically find un-paid invoices from tables bellow:
Invoices Table
InvoiceID, Date CustomerID, Amount
1 06/01/2022 1 5000.00
2 08/03/2022 1 4000.00
3 08/25/2022 1 3000.00
4 09/05/2022 1 4500.00
5 09/25/2022 1 4500.00
6 010/10/2022 1 2000.00
7 11/20/2022 1 2500.00
Payments Table:-
PaymentID Date CustomerID Amount
1 06/10/2022 1 3000.00
2 06/25/2022 1 4000.00
3 07/15/2022 1 2000.00
4 09/10/2022 1 3000.00
5 10/22/2022 1 4000.00
6 10/24/2022 1 1500.00
7 10/28/2022 1 1000.00
8 11/14/2022 1 500.00
Try to start with this:
SELECT I.CustomerID
, I.AmountTotal-ISNULL(P.AmountTotal,0) as AmountDiff
FROM
( SELECT CustomerID
, SUM(Amount) AmountTotal
FROM <invoices_table>
GROUP
BY CustomerID
) I
LEFT
OUTER
JOIN
( SELECT CustomerID
, SUM(Amount) AmountTotal
FROM <payments_table>
GROUP
BY CustomerID
) P
ON I.CustomerID = P.CustomerID
WHERE I.AmountTotal <= P.AmountTotal

How to count number of months in T-SQL

I've got a problem in SQL Server.
"Whate'er is well conceived is clearly said, And the words to say it flow with ease", Nicolas Boileau-Despreaux
Well, I don't think I'll be able to make it clear but I'll try ! And I'd like to apologize for my bad english !
I've got this table :
id ind lvl result date
1 1 a 3 2017-01-31
2 1 a 3 2017-02-28
3 1 a 1 2017-03-31
4 1 a 1 2017-04-30
5 1 a 1 2017-05-31
6 1 b 1 2017-01-31
7 1 b 3 2017-02-28
8 1 b 3 2017-03-31
9 1 b 1 2017-04-30
10 1 b 1 2017-05-31
11 2 a 3 2017-01-31
12 2 a 1 2017-02-28
13 2 a 3 2017-03-31
14 2 a 1 2017-04-30
15 2 a 3 2017-05-31
I'd like to count the number of month the combo {ind, lvl} remain in the result 1 before re-initializing the number of month to 0 if the result is not 1.
Clearly, I need to get something like that :
id ind lvl result date BadResultRemainsFor%Months
1 1 a 3 2017-01-31 0
2 1 a 3 2017-02-28 0
3 1 a 1 2017-03-31 1
4 1 a 1 2017-04-30 2
5 1 a 1 2017-05-31 3
6 1 b 1 2017-01-31 1
7 1 b 3 2017-02-28 0
8 1 b 3 2017-03-31 0
9 1 b 1 2017-04-30 1
10 1 b 1 2017-05-31 2
11 2 a 3 2017-01-31 0
12 2 a 1 2017-02-28 1
13 2 a 3 2017-03-31 0
14 2 a 1 2017-04-30 1
15 2 a 3 2017-05-31 0
So that if I was looking for the number of months the result was 1 for the date 2017-05-31 with the id 1 and the lvl a, I know it's been 3 months.
Assume all the date the the end day of month:
;WITH tb(id,ind,lvl,result,date) AS(
select 1,1,'a',3,'2017-01-31' UNION
select 2,1,'a',3,'2017-02-28' UNION
select 3,1,'a',1,'2017-03-31' UNION
select 4,1,'a',1,'2017-04-30' UNION
select 5,1,'a',1,'2017-05-31' UNION
select 6,1,'b',1,'2017-01-31' UNION
select 7,1,'b',3,'2017-02-28' UNION
select 8,1,'b',3,'2017-03-31' UNION
select 9,1,'b',1,'2017-04-30' UNION
select 10,1,'b',1,'2017-05-31' UNION
select 11,2,'a',3,'2017-01-31' UNION
select 12,2,'a',1,'2017-02-28' UNION
select 13,2,'a',3,'2017-03-31' UNION
select 14,2,'a',1,'2017-04-30' UNION
select 15,2,'a',3,'2017-05-31'
)
SELECT t.id,t.ind,t.lvl,t.result,t.date
,CASE WHEN t.isMatched=1 THEN ROW_NUMBER()OVER(PARTITION BY t.ind,t.lvl,t.id-t.rn ORDER BY t.id) ELSE 0 END
FROM (
SELECT t1.*,c.MonthDiff,CASE WHEN c.MonthDiff=t1.result THEN 1 ELSE 0 END AS isMatched
,CASE WHEN c.MonthDiff=t1.result THEN ROW_NUMBER()OVER(PARTITION BY t1.ind,t1.lvl,CASE WHEN c.MonthDiff=t1.result THEN 1 ELSE 0 END ORDER BY t1.id) ELSE null END AS rn
FROM tb AS t1
LEFT JOIN tb AS t2 ON t1.ind=t2.ind AND t1.lvl=t2.lvl AND t2.id=t1.id-1
CROSS APPLY(VALUES(ISNULL(DATEDIFF(MONTH,t2.date,t1.date),1))) c(MonthDiff)
) AS t
ORDER BY t.id
id ind lvl result date
----------- ----------- ---- ----------- ---------- --------------------
1 1 a 3 2017-01-31 0
2 1 a 3 2017-02-28 0
3 1 a 1 2017-03-31 1
4 1 a 1 2017-04-30 2
5 1 a 1 2017-05-31 3
6 1 b 1 2017-01-31 1
7 1 b 3 2017-02-28 0
8 1 b 3 2017-03-31 0
9 1 b 1 2017-04-30 1
10 1 b 1 2017-05-31 2
11 2 a 3 2017-01-31 0
12 2 a 1 2017-02-28 1
13 2 a 3 2017-03-31 0
14 2 a 1 2017-04-30 1
15 2 a 3 2017-05-31 0
By slightly tweaking your input data and slightly tweaking how we define the requirement, it becomes quite simple to produce the expected results.
First, we tweak your date values so that the only thing that varies is the month and year - the days are all the same. I've chosen to do that my adding 1 day to each value1. The fact that this produces results which are one month advanced doesn't matter here, since all values are similarly transformed, and so the monthly relationships stay the same.
Then, we introduce a numbers table - here, I've assumed a small fixed table is adequate. If it doesn't fit your needs, you can easily locate examples online for creating a large fixed numbers table that you can use for this query.
And, finally, we recast the problem statement. Instead of trying to count months, we instead ask "what's the smallest number of months, greater of equal to zero, that I need to go back from the current row, to locate a row with a non-1 result?". And so, we produce this query:
declare #t table (id int not null,ind int not null,lvl varchar(13) not null,
result int not null,date date not null)
insert into #t(id,ind,lvl,result,date) values
(1 ,1,'a',3,'20170131'), (2 ,1,'a',3,'20170228'), (3 ,1,'a',1,'20170331'),
(4 ,1,'a',1,'20170430'), (5 ,1,'a',1,'20170531'), (6 ,1,'b',1,'20170131'),
(7 ,1,'b',3,'20170228'), (8 ,1,'b',3,'20170331'), (9 ,1,'b',1,'20170430'),
(10,1,'b',1,'20170531'), (11,2,'a',3,'20170131'), (12,2,'a',1,'20170228'),
(13,2,'a',3,'20170331'), (14,2,'a',1,'20170430'), (15,2,'a',3,'20170531')
;With Tweaked as (
select
*,
DATEADD(day,1,date) as dp1d
from
#t
), Numbers(n) as (
select 0 union all select 1 union all select 2 union all select 3 union all select 4
union all
select 5 union all select 6 union all select 7 union all select 8 union all select 9
)
select
id, ind, lvl, result, date,
COALESCE(
(select MIN(n) from Numbers n1
inner join Tweaked t2
on
t2.ind = t1.ind and
t2.lvl = t1.lvl and
t2.dp1d = DATEADD(month,-n,t1.dp1d)
where
t2.result != 1
),
1) as [BadResultRemainsFor%Months]
from
Tweaked t1
The COALESCE is just there to deal with the edge case, such as for your 1,b data, where there is no previous row with a non-1 result.
Results:
id ind lvl result date BadResultRemainsFor%Months
----------- ----------- ------------- ----------- ---------- --------------------------
1 1 a 3 2017-01-31 0
2 1 a 3 2017-02-28 0
3 1 a 1 2017-03-31 1
4 1 a 1 2017-04-30 2
5 1 a 1 2017-05-31 3
6 1 b 1 2017-01-31 1
7 1 b 3 2017-02-28 0
8 1 b 3 2017-03-31 0
9 1 b 1 2017-04-30 1
10 1 b 1 2017-05-31 2
11 2 a 3 2017-01-31 0
12 2 a 1 2017-02-28 1
13 2 a 3 2017-03-31 0
14 2 a 1 2017-04-30 1
15 2 a 3 2017-05-31 0
1An alternative way to perform the adjustment is to use a DATEADD/DATEDIFF pair to perform a "floor" operation against the dates:
DATEADD(month,DATEDIFF(month,0,date),0) as dp1d
Which resets all of the date values to be the first of their own month rather than the following month. This may fell more "natural" to you, or you may already have such values available in your original data.
Assuming the dates are continously increasing in month, you can use window function like so:
select
t.id, ind, lvl, result, dat,
case when result = 1 then row_number() over (partition by grp order by id) else 0 end x
from (
select t.*,
dense_rank() over (order by e, result) grp
from (
select
t.*,
row_number() over (order by id) - row_number() over (partition by ind, lvl, result order by id) e
from your_table t
order by id) t ) t;

mssql join criteria with the same table

Just need a little help. so I have this calendar table here sqlfiddle.com/#!3/5d8a9 There are 2 flags (M, W) indicating Month or Week. I need to do a join with TBL2 (below) that has a weekly date field. so I will join TBL2 on the weekstartdate with Cal table on start date (with W flag) but I need to return the startdate with the 'M' flag if the weekstartdate falls between start and end date. Does it make sense?
TBL2:
prod_id weeknum wkstartdate postingDate qty
----------------------------------------------------------------
1043890 5 2015-01-25 2016-01-18 3
1043890 6 2015-02-01 2016-01-18 6
1043890 7 2015-02-08 2016-01-18 2
1043890 8 2015-02-15 2016-01-18 0
...
1043890 50 2015-12-06 2016-01-18 1
1043890 51 2015-12-13 2016-01-18 2
1043890 52 2015-12-20 2016-01-18 7
Desired Result:
==================
prod_id weeknum wkstartdate postingDate qty Period
----------------------------------------------------------------------------
1043890 5 2015-01-25 2016-01-18 3 2015-01-25
1043890 6 2015-02-01 2016-01-18 6 2015-01-25
1043890 7 2015-02-08 2016-01-18 2 2015-01-25
1043890 8 2015-02-15 2016-01-18 0 2015-01-25
1043890 10 2015-03-01 2016-01-18 0 2015-03-01
...
1043890 50 2015-12-06 2016-01-18 1 2015-11-22
1043890 51 2015-12-13 2016-01-18 2 2015-11-22
1043890 52 2015-12-20 2016-01-18 7 2015-11-22
If it makes sense, I'm trying to check if weekstartdate falls between a range of dates (startdate-enddate) with a flag of M, then bring the startdate and either update that record in the temp table or create a temp table with the new column added to each record.
Thanks.
what I understood is you trying to join table2 on weekstarttable with cal table on startdate and you want to modify flag if week start date falls between start date and end date.
if got it correct, try the following query.
select t2.prod_id,t2.weeknum,c.startdate
,case when t2.wkstartdate between c.startdate and c.enddate
then 'M' else null end modifiedflag,
c.flag as originalflag
from cal c,table2 t2
where c.flag ='W' and t2.wkstartdate = c.startdate
and t2.wkstartdate between c.startdate and c.enddate;

Merge two tables while dragging one column from one table to the other

With Sql Server 2014:
I have two tables - Events and Locations, that share a time column and I need to merge them into one table order by time. In the Events table there is an Event column that I need to place in all the Locations row following that event (time wise), here is an example:
Events:
time event
------------
09:00 2
09:10 3
10:15 1
10:17 2
10:30 3
Locations:
time X Y
-------------
09:01 1 3
09:02 2 3
09:05 4 1
09:09 6 4
09:10 7 8
09:11 8 8
09:12 9 7
10:17 1 2
10:19 5 4
10:20 4 3
10:25 5 4
10:28 3 5
Merged Table:
time X Y event
--------------------
09:00 0 0 2
09:01 1 3 2 <
09:02 2 3 2 <
09:05 4 1 2 <
09:09 6 4 2 <
09:10 0 0 3
09:10 7 8 3 <
09:11 8 8 3 <
09:12 9 7 3 <
10:15 0 0 1
10:17 0 0 2
10:17 1 2 2 <
10:19 5 4 2 <
10:20 4 3 2 <
10:25 5 4 2 <
10:28 3 5 2 <
10:30 0 0 3
The elements that mark with '<' are the inserted Events.
Any ideas and help on how to perform this task is welcome.
You can use UNION ALL and APPLY:
SQL Fiddle
SELECT
[Time], X = 0, Y = 0, [Event]
FROM [Events]
UNION ALL
SELECT l.*, x.Event
FROM Locations l
CROSS APPLY(
SELECT TOP 1 *
FROM [Events]
WHERE [Time] <= l.[Time]
ORDER BY [Time] DESC
)x
ORDER BY [Time]

How to split rows recursively

I've following table:
Id CreationDate FromEntryNo ToEntryNo
1 2013-01-01 1 4
2 2013-01-03 5 8
3 2013-01-05 9 11
...
I want to split this into multiple rows to have a list with all consecutive EntryNo, something like this:
Id CreationDate FromEntryNo ToEntryNo EntryNo
1 2013-01-01 1 4 1
1 2013-01-01 1 4 2
1 2013-01-01 1 4 3
1 2013-01-01 1 4 4
2 2013-01-03 5 8 5
2 2013-01-03 5 8 6
2 2013-01-03 5 8 7
2 2013-01-03 5 8 8
3 2013-01-05 9 11 9
3 2013-01-05 9 11 10
3 2013-01-05 9 11 11
...
My first attempt is CTE with recursion, but it doesn't work:
with cte as
(select gr.Id, gr.CreationDate, gr.FromEntryNo, gr.ToEntryNo, gr.FromEntryNo as [EntryNo]
from dbo.[Register] gr
union all
select No, CreationDate, FromEntryNo, ToEntryNo, EntryNo + 1 from cte where EntryNo <= ToEntryNo
)
select Id, CreationDate, FromEntryNo, ToEntryNo, EntryNo from cte
<
Any idea how to do this using one SQL query?
with cte as
(select gr.Id, gr.CreationDate, gr.FromEntryNo, gr.ToEntryNo,
gr.FromEntryNo as [EntryNo]
from dbo.[Register] gr
union all
select Id, CreationDate, FromEntryNo,
ToEntryNo, EntryNo + 1
from cte where EntryNo < ToEntryNo
)
select Id, CreationDate, FromEntryNo, ToEntryNo, EntryNo
from cte
ORDER BY Id,EntryNo

Resources