mssql join criteria with the same table - sql-server

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;

Related

How to increase the month by one in a date based on condition in SQL Server

I am trying to to extend the valid_till date for a month of tenants who have reference id more than two times.
refid, referrer_id, referrer_bonus_amount, referral_valid, valid_from, valid_till
1 2 2500 1 2015-07-05 2015-09-05
2 3 2500 1 2015-07-05 2015-09-05
3 5 1000 0 2015-12-13 2016-02-13
4 6 2500 0 2016-04-25 2016-06-24
5 10 1000 1 2015-07-01 2015-09-01
6 12 2500 1 2015-05-12 2015-07-12
7 13 2500 0 2015-08-05 2015-10-05
8 20 1000 1 2016-02-05 2016-04-05
9 2 2500 0 2015-08-12 2015-09-12
10 5 91000 1 2016-02-18 2016-04-18
11 20 1500 1 2016-06-19 2016-08-19
12 9 2500 0 2015-11-15 2016-01-15
13 13 91000 1 2016-02-01 2016-04-01
14 5 1000 1 2016-04-25 2016-06-24
To update the table (t) to add 1 month to the valid_till date for those refid that appear in referrer_id more than two times using exists() with having count(*) > 2:
update t
set valid_till = dateadd(month,1,valid_till)
output inserted.*
from t
where exists (
select 1
from t as i
where i.referrer_id = t.refid
group by referrer_id
having count(*) > 2
)
rextester demo: http://rextester.com/WXZC31875
output:
+-------+-------------+-----------------------+----------------+------------+------------+
| refid | referrer_id | referrer_bonus_amount | referral_valid | valid_from | valid_till |
+-------+-------------+-----------------------+----------------+------------+------------+
| 5 | 10 | 1000 | 1 | 2015-07-01 | 2015-10-01 |
+-------+-------------+-----------------------+----------------+------------+------------+

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;

Need select 2 rows from Table2, which is joined with Table1. See description

For example i have a Table1:
ID Specified TIN Value DateCreated
----------------------------------
1 0 tin1 45 2014-12-30
2 1 tin2 34 2013-01-05
3 0 tin3 23 2015-02-20
4 3 tin4 47 2013-06-04
5 3 tin5 12 2012-04-02
And a Table2:
ID Table1ID RegistrationDate
----------------------------------
1 1 2015-10-12
2 2 2015-07-21
3 1 2015-11-26
4 1 2015-12-04
5 2 2015-09-18
I need select all columns from Table1 with first and last RegistrationDate column in Table2. The answer should be
ID Specified TIN Value DateCreated FirstRegDate LastRegDate
---------------------------------------------------------------
1 0 tin1 45 2014-12-30 2015-10-12 2015-12-04
2 1 tin2 34 2013-01-05 2015-07-21 2015-09-18
3 0 tin3 23 2015-02-20 NULL NULL
4 3 tin4 47 2013-06-04 NULL NULL
5 3 tin5 12 2012-04-02 NULL NULL
Hi one possible solution can be something similar to pseudo query below(if you can prepare the tables I will modify to reflect actual query)
SELECT table1.*, inlineTable2.firstRegDate, inlineTable2.lastRegDate
FROM Table1
LEFT JOIN
(
SELECT
Table1ID AS id,
MIN(registrationDate) as firstRegDate,
MAX(regsitrationDate) as lastRegDate
FROM table2
GROUP BY table1ID
) AS inlineTable2
ON table1.id = inlineTable2.id
You can group by all columns in table1, and look up the minumum and maximum registration date for the group:
select ID
, Specified
, ... other columns from table1 ...
, min(RegistrationDate)
, max(RegistrationDate)
from Table1 t1
left join
Table2 t2
on t1.ID = t2.Table1ID
group by
ID
, Specified
, ... other columns from table1 ...

How to update record based on value of next record in SQL Server 2008

I like to update a column based on a value of the next record:
resid startdate enddate weekday hours
-----------------------------------------------
2980 2013-09-23 2014-12-31 1 6
2980 2013-09-23 2014-12-31 2 6
2980 2013-09-23 2014-12-31 3 6
2980 2013-09-23 2014-12-31 4 6
2980 2013-09-23 2014-12-31 5 6
2980 2015-01-01 NULL 1 6,8
2980 2015-01-01 NULL 2 6,8
2980 2015-01-01 NULL 3 6,8
2980 2015-01-01 NULL 4 6,8
2980 2015-01-01 NULL 5 6,8
2980 2015-07-01 NULL 1 6
2980 2015-07-01 NULL 2 6
2980 2015-07-01 NULL 3 6
2980 2015-07-01 NULL 4 6
2980 2015-07-01 NULL 5 6
I like to update the NULL value in column enddate. It needs to get a value of the next startdate - 1 day.
For instance, for all records with startdate 2015-01-01, the column enddate needs to be updated with 2015-07-01 - 1 day.
Is there someone who has a solution?
update TableName set enddate = dateadd(day,1,startdate)
One way to do it is with a subquery:
UPDATE t1
SET enddate = (SELECT TOP 1 DATEADD(DAY, -1, startdate)
FROM YourTable t2
WHERE t1.startdate < t2.startdate
ORDER BY t2.startdate)
FROM YourTable t1
WHERE t1.enddate is null

How to get TOP (1) row within each Group in sql server 2000

I have some following set of data from where I want to select Top 1 row for each PK_PatientId based on the current order
PK_PatientId PK_PatientVisitId PK_VisitProcedureId DateSort
------------ ----------------- ------------------- -----------------------
1 4 4 2009-06-22 00:00:00.000
1 3 3 2009-06-22 00:00:00.000
1 2 2 2010-03-11 00:00:00.000
1 1 1 2010-03-11 00:00:00.000
5 6 6 2009-05-24 00:00:00.000
5 5 5 2009-11-07 00:00:00.000
7 7 7 2009-05-24 00:00:00.000
8 8 8 2009-05-24 00:00:00.000
9 9 9 2009-05-24 00:00:00.000
10 10 10 2009-05-24 00:00:00.000
Query that lead me to this result is
SELECT
P.PK_PatientId
, PV.PK_PatientVisitId
, MAX(TVP.PK_VisitProcedureId) AS PK_VisitProcedureId
, MAX(PV.LastUpdated) AS DateSort
--, Row_Number() OVER (Partition BY PK_PatientId ORDER BY PV.PK_PatientVisitId DESC) AS RowNo
FROM
dbo.M_Patient AS P
INNER JOIN
dbo.M_PatientVisit AS PV
ON
P.PK_PatientId = PV.FK_PatientId
INNER JOIN
dbo.TX_VisitProcedure AS TVP
ON
PV.PK_PatientVisitId = TVP.FK_PatientVisitId
WHERE
(P.IsActive = 1)
AND
(PV.IsActive = 1)
AND
(TVP.IsActive = 1)
GROUP BY
PK_PatientId
, PK_PatientVisitId
ORDER BY
PK_PatientId
, PK_PatientVisitId DESC
and I have to get the remaining functionality that I was doing with Row Number function by taking RowNo=1. But Now I have to take this procedure to SQL 2000 due to which this function can't be used.
Desired Result is
PK_PatientId PK_PatientVisitId PK_VisitProcedureId DateSort RowNo
------------ ----------------- ------------------- ----------------------- --------------------
1 4 4 2009-06-22 00:00:00.000 1
5 6 6 2009-05-24 00:00:00.000 1
7 7 7 2009-05-24 00:00:00.000 1
8 8 8 2009-05-24 00:00:00.000 1
9 9 9 2009-05-24 00:00:00.000 1
which I am getting when using Row_Number in sql 2005. I want same result using sql 2000 only.
I have to use SQL 2000
You just need to strap this to the end of your WHERE clause:
AND NOT EXISTS (
SELECT *
FROM dbo.M_PatientVisit PV2
WHERE P.PK_PatientId = PV2.FK_PatientId
AND PV2.PK_PatientVisitId > PV.PK_PatientVisitId
)
...which will result in the query returning "the patient visits for patients where there does not exist another visit for that patient with a higher ID" - that is, you'll get the visits with the highest IDs.
Note that you'll need to include the other logic in the WHERE clause in this subquery in order to ensure that the bits are active etc.
Would you mind use temporary table in your procedure? I mean that you can insert max(PatientVisitId) rows into a temporary table.

Resources