Use join with CTE - sql-server

I have a table in which i am inserting some records every week. There is a column for Date. I want to compare the data of last week and this week using column key. Below is my table:
Name Date Key
ABC 07 June 1
BAC 07 June 2
WSD 07 June 3
QWE 14 June 9
QWT 14 June 2
DEF 14 June 1
CXZ 14 June 6
I want the data of 14 June in which key is same as in data of 07th june.
Desired output:
Name Date Key
QWT 14 June 2
DEF 14 June 1
I am using CTE to join but i am not getting the desired results.
;WITH T1
AS
(SELECT * FROM [Table] where [Date]= '07 June'),
T2
AS
(SELECT * FROM [Table] where [Date]= '14 June')
SELECT *
FROM T2
INNER JOIN T1 ON T1.[KEY] = T2.[KEY];

What you have should be returning the results you stated that you want. I would maybe simplify this a little bit to a single query with a self join. Something like this.
select t2.*
from [Table] t
join [Table] t2 on t.MyKey = t2.MyKey
where t.MyDate = '07 June'
and t2.MyDate = '14 June'

If you want the data of 14 June in which key is the same as in data of 07th June. You can use intersect:
select
t1.*
from
table
as t1
where
t1.MyDate = '07 June'
intersect select
t2.*
from
table
as t2
where
t2.MyDate = '14 June

You can also think everything dynamic as below. This will return you result regardless what is the date is. this will always compare a row with the row with date 7 day less.
You can check DEMO HERE
SELECT A.*
FROM your_table A
INNER JOIN your_table B
ON A.[Key] = B.[Key] AND DATEADD(DD,7,B.[Date]+ ' 2019') = A.[Date] + ' 2019'
-- Added 2019 To make the string as date

Related

SQL join combined with new column calculation

I have two tables in SQL that look like this:
Table 1:
ID TaxYear Earnings
01 2000 2234
01 2001 123
02 2004 12344
02 2006 234
02 2007 0
02 2008 123
Table 2:
ID JobEnd
01 1998
02 2000
02 2007
I need to combine these tables to make a new column giving the number of years between TaxYear and JobEnd. However, I need this value to reset every time TaxYear passes a new JobEnd year. So my final table would look like this:
ID TaxYear Earnings YearsSinceJobEnd
01 2000 2234 2
01 2001 123 3
02 2004 12344 4
02 2006 234 6
02 2007 0 7
02 2008 123 1
For ID 02, when YearsSinceJobEnd is calculated as TaxYear minus 2000, up until TaxYear passes the new JobEnd year of 2007, when it is subsequently calculated as TaxYear minus 2007.
I'm getting very confused about how to do this. If I join the tables I end up with multiple columns per TaxYear, which I need to avoid. But I can't think how to calculate the new column without joining them.
Any help would be much appreciated.
You can use datediff() with DATETIMEFROMPARTS ():
select t1.id, t1.TaxYear, t1.Earnings,
datediff(year, DATEFROMPARTS(t2.JobEnd, 1, 1), DATEFROMPARTS(t1.TaxYear, 1, 1)) as YearsSinceJobEnd
from t1 inner join
t2
on t2.id = t1.id;
If you don't want JOIN then use APPLY :
select t1.id, t1.TaxYear, t1.Earnings,
datediff(year, DATEFROMPARTS(t2.JobEnd, 1, 1), DATEFROMPARTS(t1.TaxYear, 1, 1)) as YearsSinceJobEnd
from t1 cross apply
( select top (1) t2.JobEnd
from t2
where t2.id = t1.id and t2.JobEnd < t1.TaxYear
order by t2.JobEnd desc
) t2;
you can user CROSS APPLY to find the required JobEnd for each ID
SELECT t1.ID, t1.TaxYear, t1.Earnings,
YearsSinceJobEnd = t1.TaxYear - e.JobEnd
FROM Table1 t1
CROSS APPLY
(
SELECT JobEnd = MAX(t2.JobEnd)
FROM Table2 t2
WHERE t2.ID = t1.ID
AND t2.JobEnd < t1.TaxYear
) e

Sql comparaison nested on one column

Imagine a table :
ID Month Year Value 1
1 May 17 58
2 June 09 42
3 December 18 58
4 December 18 58
5 September 10 84
6 May 17 42
7 January 16 3
I want to return all the data that shares the same month and year where Value 1 is different. So in our example, I want to return 1 and 6 only but not 3 and 4 or any of the other entries.
Is there a way to do this? I am thinking about a combination of distinct and group by but can't seem to come up with the right answer being new to SQL.
Thanks.
It could be done without grouping, but with simple self-join:
select distinct t1.*
from [Table] t1
inner join [Table] t2 on
t1.Month = t2.Month
and t1.Year = t2.Year
and t1.Value_1 <> t2.Value_1
You can find some information and self-join examples here and here.
For each row you can examine aggregates in its group with the OVER clause. eg:
create table #t(id int, month varchar(20), year int, value int)
insert into #t(id,month,year,value)
values
(1,'May' ,17, 58 ),
(2,'June' ,09, 42 ),
(3,'December' ,18, 58 ),
(4,'December' ,18, 58 ),
(5,'September',10, 84 ),
(6,'May' ,17, 42 ),
(7,'January' ,16, 3 );
with q as
(
select *,
min(value) over (partition by month,year) value_min,
max(value) over (partition by month,year) value_max
from #t
)
select id,month,year,value
from q
where value_min <> value_max;
If I understood your question correctly, you are looking for the HAVING keyword.
If you GROUP BY Month, Year, Value_1 HAVING COUNT(*) = 1, you get all combinations of Month, Year and Value_1 that have no other occurrence.

SQL Select Sequential Dates with Additional Lookup Values

I am trying to grab a series of dates and the corresponding values (if any) that exist in my database.
I have two parameters - today (date using getDate()) - and a number of days (integer). For this example, I'm using the value 10 for the days.
Code to get the sequential dates for 10 days after today:
SELECT top 10 DATEADD(DAY, ROW_NUMBER()
OVER (ORDER BY object_id), REPLACE(getDate(),'-','')) as Alldays
FROM sys.all_objects
I now need to look up several values for each day in the sequential days code, which may or may not exist in the time table (we assume 8 hours for all dates, unless otherwise specified). The lookup would be on the field recordDateTime. If no "hours" value exists in the table cap_time for that date, I need to return a default value of 8 as the number of hours. Here's the base query:
SELECT u.FullName as UserName, d2.department,
recordDateTime, ISNULL(hours,8) as hours
FROM cap_time c
left join user u on c.userID = u.userid
left join dept d2 on u.deptID = d2.DeptID
WHERE c.userid = 38 AND u.deptID = 1
My end result for the next 10 days should be something like:
Date (sequential), Department, UserName, Number of Hours
I can accomplish this using TSQL and a temp table, but I'd like to see if this can be done in a single statement. Any help is appreciated.
Without any DDL or sample data it's hard to determine exactly what you need.
I think this will get you pretty close (note my comments):
-- sample data
------------------------------------------------------------------------------------------
DECLARE #table TABLE
(
fullName varchar(10),
department varchar(10),
[hours] tinyint,
somedate date
);
INSERT #table VALUES
('bob', 'sales', 5, getdate()+1),
('Sue', 'marketing', 3, getdate()+2),
('Sue', 'sales', 12, getdate()+4),
('Craig', 'sales', 4, getdate()+8),
('Joe', 'sales', 18, getdate()+9),
('Fred', 'sales', 10, getdate()+10);
--SELECT * FROM #table
;
-- solution
------------------------------------------------------------------------------------------
WITH alldays([day]) AS -- logic to get your dates for a LEFT date table
(
SELECT TOP (10)
CAST(DATEADD
(
DAY,
ROW_NUMBER() OVER (ORDER BY object_id),
getdate()
) AS date)
FROM sys.all_objects
)
SELECT d.[day], t.fullName, department, [hours] = ISNULL([hours], 8)
FROM alldays d
LEFT JOIN #table t ON d.[day] = t.somedate;
Results:
day fullName department hours
---------- ---------- ---------- -----
2017-04-12 bob sales 5
2017-04-13 Sue marketing 3
2017-04-14 NULL NULL 8
2017-04-15 Sue sales 12
2017-04-16 NULL NULL 8
2017-04-17 NULL NULL 8
2017-04-18 NULL NULL 8
2017-04-19 Craig sales 4
2017-04-20 Joe sales 18
2017-04-21 Fred sales 10
Maybe a subquery and the in statement, like:
SELECT u.FullName as UserName, d2.department,
recordDateTime, ISNULL(hours,8) as hours
FROM cap_time c
left join user u on c.userID = u.userid
left join dept d2 on u.deptID = d2.DeptID
WHERE c.userid = 38 AND u.deptID = 1 and recordDateTime in
(SELECT top 10 DATEADD(DAY, ROW_NUMBER()
OVER (ORDER BY object_id), REPLACE(getDate(),'-','')) as Alldays
FROM sys.all_objects)

Find the min and max dates between multiple sets of dates

Given the following set of data, I'm trying to determine how I can select the start and end dates of the combined date ranges, when they intersect with each other.
For instance, for PartNum 115678, I would want my final result set to display the date ranges 2012/01/01 - 2012/01/19 (rows 1, 2 and 4 combined since the date ranges intersect) and 2012/02/01 - 2012/03/28 (row 3 since this ones does not intersect with the range found previously).
For PartNum 213275, I would want to select the only row for that part, 2012/12/01 - 2013/01/01.
Edit:
I'm currently playing around with the following SQL statement, but it's not giving me exactly what I need.
with DistinctRanges as (
select distinct
ha1.PartNum "PartNum",
ha1.StartDt "StartDt",
ha2.EndDt "EndDt"
from dbo.HoldsAll ha1
inner join dbo.HoldsAll ha2
on ha1.PartNum = ha2.PartNum
where
ha1.StartDt <= ha2.EndDt
and ha2.StartDt <= ha1.EndDt
)
select
PartNum,
StartDt,
EndDt
from DistinctRanges
Here are the results of the query shown in the edit:
You're better off having a persisted Calendar table, but if you don't, the CTE below will create it ad-hoc. The TOP(36000) part is enough to give you 10 years worth of dates from the pivot ('20100101') on the same line.
SQL Fiddle
MS SQL Server 2008 Schema Setup:
create table data (
partnum int,
startdt datetime,
enddt datetime,
age int
);
insert data select
12345, '20120101', '20120116', 15 union all select
12345, '20120115', '20120116', 1 union all select
12345, '20120201', '20120328', 56 union all select
12345, '20120113', '20120119', 6 union all select
88872, '20120201', '20130113', 43;
Query 1:
with Calendar(thedate) as (
select TOP(36600) dateadd(d,row_number() over (order by 1/0),'20100101')
from sys.columns a
cross join sys.columns b
cross join sys.columns c
), tmp as (
select partnum, thedate,
grouper = datediff(d, dense_rank() over (partition by partnum order by thedate), thedate)
from Calendar c
join data d on d.startdt <= c.thedate and c.thedate <= d.enddt
)
select partnum, min(thedate) startdt, max(thedate) enddt
from tmp
group by partnum, grouper
order by partnum, startdt
Results:
| PARTNUM | STARTDT | ENDDT |
------------------------------------------------------------------------------
| 12345 | January, 01 2012 00:00:00+0000 | January, 19 2012 00:00:00+0000 |
| 12345 | February, 01 2012 00:00:00+0000 | March, 28 2012 00:00:00+0000 |
| 88872 | February, 01 2012 00:00:00+0000 | January, 13 2013 00:00:00+0000 |

Select a distinct record, filtering is not working

Hello EVery I am new to SQl. query to result in the following records.
I have a table with records as
c1 c2 c3 c4 c5 c6
1 John 2.3.2010 12:09:54 4 7 99
2 mike 2.3.2010 13:09:59 8 6 88
3 ahmad 2.3.2010 13:09:59 1 9 19
4 Jim 23.3.2010 16:35:14 4 5 99
5 run 23.3.2010 12:09:54 3 8 12
I want to fecth only records.
i.e only 1 latest record per day. If both of them happen at the same time, sort by C1.so in 1&3 it should fetch 3.
3 ahmad 2.3.2010 14:09:59 1 9 19
4 Jim 23.3.2010 16:35:14 4 5 99
I have got a new problem in this.
If i filter the records based on conditions the last record is missing. I tried many ways but still it is failing. Here update_log is my table.
SELECT * FROM update_log t1
WHERE (t1.c3) =
(
SELECT MAX(t2.c3)
FROM update_log t2
WHERE DATEDIFF(dd,t2.c3, t1.c3) = 0
)
and t1.c3 > '02.03.2010' and t1.modified_at <= '22.03.2010'
ORDER BY t1.c3 ASC. But i am not able to retrieve the record
4 Jim 23.3.2010 16:35:14 4 5 99
I dont know this query results in only
3 ahmad 2.3.2010 14:09:59 1 9 19
The format of the column c3 is datetime. I am pumping the data into the column as
using $date = date("d.m.Y H:i",time()); -- simple date fetch of today.
Another query that i tried for the same purpose.
select * from (select convert(varchar(10), c3,104) as date, max(c3) as max_date, max(c1) as Nr from update_log group by convert(varchar(10), c3,104)) as t2 inner join update_log as t1 on (t2.max_date = t1.c3 and convert(varchar(10), c3,104) = date and t1.[c1]= Nr) WHERE t1.c3 >= '02.03.2010' and t1.c3 <= '16.04.2010' . I even tried this way..the same error last record is not coming..
Following steps should produce the results you are after
Find max c3 for every day.
Join the results with your original table, witholding only the max c1 values.
SQL Statement (Edited)
DECLARE #update_log TABLE (c1 INTEGER, c3 DATETIME)
INSERT INTO #update_log
SELECT 1, '3.2.2010 12:09:54'
UNION ALL SELECT 2, '3.2.2010 13:09:59'
UNION ALL SELECT 3, '3.2.2010 13:09:59'
UNION ALL SELECT 4, '3.23.2010 16:35:14'
UNION ALL SELECT 5, '3.23.2010 12:09:54'
SELECT c1 = MAX(l.c1), l.c3
FROM #update_log l
INNER JOIN (
SELECT c3_max = MAX(c3)
FROM #update_log
WHERE c3 > '3.2.2010 00:00:00'
AND c3 < '3.24.2010 00:00:00'
GROUP BY
CONVERT(VARCHAR(10), c3, 101)
) l_maxdate ON l_maxdate.c3_max = l.c3
GROUP BY
l.c3
Notes
You should read the FAQ regarding as to how this site operates. As has been mentioned, Stack Overflow is not intented to be used like one would use a newsreader where you ask follow-up questions after an answer has been given by creating a new answer.
You should edit your question for any additional information or use the comments. If the additional information is that much that it in effect changes the entire question, you should consider making a new question out of it.
That being said, enjoy SO.
Assuming c1 is unique, hopefully even the primary key. This also assumes the use of SQL Server 2008 for the DATE data type.
SELECT t1.*
FROM update_log t1
WHERE t1.c3 > '02.03.2010'
AND t1.modified_at <= '22.03.2010'
AND t1.c1 IN
( SELECT TOP 1 c1
FROM update_log t2
WHERE CAST(t1.c3 As DATE) = CAST(t2.c3 As DATE)
ORDER BY c3 DESC, c1 DESC
)
OK, Now i understood. actually i wrote the query for the same purpose this way.
select * from #temp
select * from
(select max(c1) as nr from
(select convert(varchar(10), c3,104) as date, max(c3) as max_date
from #temp where
convert(varchar(10),c3,104) >= '02.02.2010' and
convert(varchar(10),c3,104) <= '23.02.2010'
group by convert(varchar(10), c3,104))
as t2 inner join #temp as t1 on (t2.max_date = t1.c3 and
convert(varchar(10), c3,104) = date)
group by convert(varchar(10),max_date,104))
as t3 inner join #temp as t4 on (t3.nr = t4.c1 )
If i change these 2 lines to c3 >= '02.02.2010' and
c3 <= '24.02.2010'. It is working fine. but the query that i have posted is not able to filter the records properly based on dates.
I want to know where i went to wrong to enhance my knoweldge rather than just copying ur query:-)

Resources