Self join using case statement in SQL Server - sql-server

Below is the data in a table Star. I want a query which returns only 1 record per StarID per assessdate but if there are same assessdate for one starid then compare the askdate and return that record which has most recent askdate.
StarID | assessdate | artid | pep |manager | Notes | followup| askdate
DEC1660 | 2016-05-18 00:00:00.000 | 20979 | Yes |BRIGGS, SIMON |NULL | 6 Weeks | NULL
DEC1660 | 2016-05-19 00:00:00.000 | 20982 | No |BRIGGS, SIMON |Other, sdf, AZT, TDF, RAL | 12 Weeks| 2016-05-11 00:00:00.000
ANW4477 | 2016-05-27 00:00:00.000 |21008 | Yes |Mundt, Susan |NFV, DRV, MVC, Other, test| 6 Weeks | 2016-05-27 00:00:00.000
ANW4477 | 2016-05-28 00:00:00.000 |21011 | No |Henley, Rebecca |NULL | 12 Weeks| NULL
REP2893 | 2016-05-30 00:00:00.000 |21305 | Yes |Henley, Rebecca |AZT, 3TC | 12 Weeks| 2016-05-30 00:00:00.000
REP2893 | 2016-05-30 00:00:00.000 |21305 | Yes |Henley, Rebecca |TDF, FTC | 12 Weeks| 2016-06-02 00:00:00.000
Thanks in advance!

WITH X AS (
Select *
, ROW_NUMBER() OVER (PARTITION BY StarID, assessdate
ORDER BY askdate DESC) rn
FROM Star )
SELECT *
FROM X
WHERE rn = 1

Related

SQL Get 12 weeks as columns

i need help on the following.
I have the basic query below:
select count(transactions)
from tx
where customer = 'AA'
This gives me a count of all transactions for the relevant client.
What I want is a query that gives me the same output but broken down into the LATEST last 12 weeks (Monday-Sunday is one full week). These values should be presented as 12 columns with the header of each column presented as the last date of the week (ie Sunday's date).
Furthermore the total transactions are split into status- failed and success. I would like the rows of the transactions to be failed and success so the final table would look like this:
25/03/2018 (week 1)| 01/04/2018| ........ |17/06/2018 << (week 12)
Success 100 | 200 | ........ | 150
Failed 3 | 4 | ........ | 6
Any ideas how this can be done?
Thanks you in advance
Returning pivoted data is usually a lot more hassle than it is worth and you should just leave this up to your presentation layer, which will handle your dynamic columns with much more grace. Regardless of the presentation layer you are using (SSRS, Excel, Power BI, etc), you will get the most flexibility by providing it a standard set of unpivoted data:
declare #t table (id int, TransactionDate date, Outcome varchar(8));
insert into #t values
(1,getdate()-1,'Success')
,(2,getdate()-2,'Success')
,(3,getdate()-2,'Success')
,(4,getdate()-3,'Success')
,(5,getdate()-6,'Failed')
,(6,getdate()-6,'Success')
,(7,getdate()-7,'Success')
,(8,getdate()-8,'Success')
,(9,getdate()-8,'Success')
,(10,getdate()-10,'Success')
,(11,getdate()-10,'Failed')
,(12,getdate()-11,'Success')
,(13,getdate()-13,'Success')
;
with w(ws) as(select dateadd(week, datediff(week,0,getdate())-w, 0) -- Monday at the start of the week, minus w.w weeks for all 12
from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11)) as w(w)
)
,d(ws,d) as(select w.ws
,dateadd(day,d.d,w.ws) as d -- Each day that makes up each week for equijoin to Transactions table
from w
cross join (values(0),(1),(2),(3),(4),(5),(6)) as d(d)
)
select d.ws as WeekStart
,t.Outcome
,count(t.TransactionDate) as Transactions
from d
left join #t as t
on d.d = t.TransactionDate
group by d.ws
,t.Outcome
order by d.ws
,t.Outcome;
Output:
+-------------------------+---------+--------------+
| WeekStart | Outcome | Transactions |
+-------------------------+---------+--------------+
| 2018-04-09 00:00:00.000 | NULL | 0 |
| 2018-04-16 00:00:00.000 | NULL | 0 |
| 2018-04-23 00:00:00.000 | NULL | 0 |
| 2018-04-30 00:00:00.000 | NULL | 0 |
| 2018-05-07 00:00:00.000 | NULL | 0 |
| 2018-05-14 00:00:00.000 | NULL | 0 |
| 2018-05-21 00:00:00.000 | NULL | 0 |
| 2018-05-28 00:00:00.000 | NULL | 0 |
| 2018-06-04 00:00:00.000 | NULL | 0 |
| 2018-06-11 00:00:00.000 | NULL | 0 |
| 2018-06-11 00:00:00.000 | Success | 2 |
| 2018-06-18 00:00:00.000 | NULL | 0 |
| 2018-06-18 00:00:00.000 | Failed | 2 |
| 2018-06-18 00:00:00.000 | Success | 5 |
| 2018-06-25 00:00:00.000 | NULL | 0 |
| 2018-06-25 00:00:00.000 | Success | 4 |
+-------------------------+---------+--------------+

T-SQL Join two tables where the join condition is dependant on values in both tables

I have a query which combines data from two tables.
Policy table
PolicyID PolicyNumber PolicyStartDate
48 FCO100009 2015-06-01 00:00:00.000
49 FCO100009 2016-06-01 00:00:00.000
Claim Table
ClaimID ClaimReference PolicyNumber IncidentDatetime NotificationDatetime Version
30 287 FCO100009 2015-11-06 00:00:00.000 2015-11-27 00:00:00.000 4. Claim - Incident Date
223 259 FCO100009 2015-11-03 00:00:00.000 2015-11-20 00:00:00.000 4. Claim - Incident Date
1367 988 FCO100009 2016-04-15 00:00:00.000 2016-04-21 00:00:00.000 4. Claim - Incident Date
1561 1859 FCO100009 2016-09-14 00:00:00.000 2016-09-19 00:00:00.000 4. Claim - Incident Date
1741 443275 FCO100009 2016-05-11 00:00:00.000 2016-05-12 00:00:00.000 4. Claim - Incident Date
1742 991 FCO100009 2016-04-20 00:00:00.000 2016-04-21 00:00:00.000 4. Claim - Incident Date
2038 287 FCO100009 2015-11-06 00:00:00.000 2015-11-27 00:00:00.000 5. Claim - Notification Date
3744 259 FCO100009 2015-11-03 00:00:00.000 2015-11-20 00:00:00.000 5. Claim - Notification Date
3745 991 FCO100009 2016-04-20 00:00:00.000 2016-04-21 00:00:00.000 5. Claim - Notification Date
4502 1859 FCO100009 2016-09-14 00:00:00.000 2016-09-19 00:00:00.000 5. Claim - Notification Date
4639 988 FCO100009 2016-04-15 00:00:00.000 2016-04-21 00:00:00.000 5. Claim - Notification Date
6600 443275 FCO100009 2016-05-11 00:00:00.000 2016-05-12 00:00:00.000 5. Claim - Notification Date
There are 2 records for the Policy with different Policy Start Dates and a 2 versions of each claim record where the Version field is either Claim Incident Date or Claim Notification Date.
What I am attempting to accomplish is joining the two tables on PolicyNumber and then setting the PolicyStartDate value in the results to be the maximum value from Policy.PolicyStartDate where the PolicyStartDate is less than the NotificationDate when Version = NotificationDate OR PolicyStartDate is less than the Incident Date when Version = IncidentDate.
Please note that this is using financial NOT Calendar years and in this case the year of account runs from April to March.
Here is my current query which doesn't produce the correct answer:
SELECT cds.ClaimID,
cds.ClaimReference,
p.policyID,
p.PolicyStartDate,
cds.IncidentDatetime,
cds.NotificationDatetime,
cds.[Version]
FROM dbo.ClaimDataStaging cds
INNER JOIN dbo.[Policy] p
ON p.PolicyNumber = cds.PolicyNumber
AND p.PolicyStartDate < CASE WHEN cds.[Version] = '4. Claim - Incident Date' THEN cds.IncidentDatetime
WHEN cds.[Version] = '5. Claim - Notification Date' THEN cds.NotificationDatetime END
WHERE cds.PolicyNumber = 'FCO100009'
ORDER BY cds.[Version], cds.ClaimReference;
GO
Any help or advice much appreciated.
As far as I understood your question and your problem (duplicates caused by condition on date < date which catches former policy too), you can try this query too.
It use LEAD() function to calculate a sort of Enddate (I used IS NULL to to catch last policy, but you can change it adapting to your needs).
I moved the CASE in an inner query to avoid repeating of it in the WHERE clause.
SELECT cds.ClaimID,
cds.ClaimReference,
p.policyID,
p.PolicyStartDate,
cds.IncidentDatetime,
cds.NotificationDatetime,
cds.[Version]
FROM (SELECT ClaimID, ClaimReference, IncidentDatetime,NotificationDatetime,[Version], PolicyNumber
, CASE WHEN [Version] = '4. Claim - Incident Date' THEN IncidentDatetime
WHEN [Version] = '5. Claim - Notification Date' THEN NotificationDatetime END AS CheckDate
FROM dbo.ClaimDataStaging) cds
INNER JOIN (SELECT policyID, PolicyNumber, PolicyStartDate
, LEAD(PolicyStartDate) OVER (PARTITION BY PolicyNumber ORDER BY PolicyStartDate) AS PolicyEndDate FROM dbo.Policy ) p
ON p.PolicyNumber = cds.PolicyNumber
AND p.PolicyStartDate < CheckDate
AND (p.PolicyEndDate IS NULL OR p.PolicyEndDate>=CheckDate)
WHERE cds.PolicyNumber = 'FCO100009'
ORDER BY cds.[Version], cds.ClaimReference;
Output:
+---------+----------------+----------+-------------------------+-------------------------+-------------------------+------------------------------+
| ClaimID | ClaimReference | policyID | PolicyStartDate | IncidentDatetime | NotificationDatetime | Version |
+---------+----------------+----------+-------------------------+-------------------------+-------------------------+------------------------------+
| 223 | 259 | 48 | 2015-06-01 00:00:00.000 | 2015-11-03 00:00:00.000 | 2015-11-20 00:00:00.000 | 4. Claim - Incident Date |
| 30 | 287 | 48 | 2015-06-01 00:00:00.000 | 2015-11-06 00:00:00.000 | 2015-11-27 00:00:00.000 | 4. Claim - Incident Date |
| 1367 | 988 | 48 | 2015-06-01 00:00:00.000 | 2016-04-15 00:00:00.000 | 2016-04-21 00:00:00.000 | 4. Claim - Incident Date |
| 1742 | 991 | 48 | 2015-06-01 00:00:00.000 | 2016-04-20 00:00:00.000 | 2016-04-21 00:00:00.000 | 4. Claim - Incident Date |
| 1561 | 1859 | 49 | 2016-06-01 00:00:00.000 | 2016-09-14 00:00:00.000 | 2016-09-19 00:00:00.000 | 4. Claim - Incident Date |
| 1741 | 443275 | 48 | 2015-06-01 00:00:00.000 | 2016-05-11 00:00:00.000 | 2016-05-12 00:00:00.000 | 4. Claim - Incident Date |
| 3744 | 259 | 48 | 2015-06-01 00:00:00.000 | 2015-11-03 00:00:00.000 | 2015-11-20 00:00:00.000 | 5. Claim - Notification Date |
| 2038 | 287 | 48 | 2015-06-01 00:00:00.000 | 2015-11-06 00:00:00.000 | 2015-11-27 00:00:00.000 | 5. Claim - Notification Date |
| 4639 | 988 | 48 | 2015-06-01 00:00:00.000 | 2016-04-15 00:00:00.000 | 2016-04-21 00:00:00.000 | 5. Claim - Notification Date |
| 3745 | 991 | 48 | 2015-06-01 00:00:00.000 | 2016-04-20 00:00:00.000 | 2016-04-21 00:00:00.000 | 5. Claim - Notification Date |
| 4502 | 1859 | 49 | 2016-06-01 00:00:00.000 | 2016-09-14 00:00:00.000 | 2016-09-19 00:00:00.000 | 5. Claim - Notification Date |
| 6600 | 443275 | 48 | 2015-06-01 00:00:00.000 | 2016-05-11 00:00:00.000 | 2016-05-12 00:00:00.000 | 5. Claim - Notification Date |
+---------+----------------+----------+-------------------------+-------------------------+-------------------------+------------------------------+
Based on the suggestions received, I was able to adjust my query to provide the required result. Here is my final code for reference:
SELECT DISTINCT
cds.ClaimID,
MAX(p.PolicyID) OVER (PARTITION BY cds.PolicyNumber) AS PolicyID,
MAX(p.PolicyStartDate) OVER (PARTITION BY cds.PolicyNumber) AS
PolicyStartDate, cds.ClaimKey, cds.ClaimReference, cds.ClaimStatus,
cds.IncidentDatetime, cds.NotificationDatetime, cds.UW_Date,
cds.IncidentType, cds.IncidentDescription, cds.OwnDamagePaid,
cds.OwnDamageReserve, cds.OwnDamageIncurred, cds.TPDamagePaid,
cds.TPDamageReserve, cds.TPDamageIncurred,
cds.BodilyInjuryPaid, cds.BodilyInjuryReserve,
cds.BodilyInjuryIncurred, cds.TotalPaid, cds.TotalReserve,
cds.EstimatedRecovery, cds.ActualRecovery, cds.TotalIncurred, cds.TotalIncurredBand,
CONVERT(VARCHAR(16), 'Current Period') AS TimeView, 1 AS ClaimCount, CONVERT(VARCHAR(48), [Version]) AS [Version]
FROM dbo.ClaimDataStaging cds
INNER JOIN dbo.UW_Calendar u
ON u.UW_Date = cds.UW_Date
LEFT OUTER JOIN dbo.[Policy] p
ON p.PolicyNumber = cds.PolicyNumber
AND p.PolicyStartDate <= CASE
WHEN cds.[Version] = '4. Claim - Incident Date' THEN cds.IncidentDatetime
WHEN cds.[Version] = '5. Claim - Notification Date' THEN cds.NotificationDatetime
END;
GO
I think you're looking for something like the query below. It will give you the max policy number based on the filter you had for the dates.
SELECT cds.ClaimID,
cds.ClaimReference,
p.policyID,
p.PolicyStartDate,
cds.IncidentDatetime,
cds.NotificationDatetime,
cds.[Version]
FROM dbo.ClaimDataStaging cds
CROSS APPLY (
SELECT PolicyStartDate = MAX(fp.PolicyStartDate)
FROM dbo.[Policy] fp
WHERE fp.PolicyNumber = cds.PolicyNumber
AND ((fp.PolicyStartDate < cds.IncidentDatetime AND cds.[Version] = '4. Claim - Incident Date')
OR (fp.PolicyStartDate < cds.NotificationDatetime AND cds.[Version] = '5. Claim - Notification Date')) sp
INNER JOIN dbo.[Policy] p ON p.PolicyNumber = cds.PolicyNumber AND p.PolicyStartDate = sp.PolicyStartDate
WHERE cds.PolicyNumber = 'FCO100009'
ORDER BY cds.[Version], cds.ClaimReference;
GO

SQL server 2000 pulling count grouped by time

I have a table like below.
Date | Time | connect |
2013-08-23 00:00:00.000 | 05.26.13 | 1 |
2013-08-23 00:00:00.000 | 05.32.11 | 1 |
2013-08-23 00:00:00.000 | 05.26.13 | 1 |
2013-08-23 00:00:00.000 | 06.02.52 | 1 |
2013-08-23 00:00:00.000 | 06.41.09 | 1 |
2013-08-23 00:00:00.000 | 06.43.12 | 1 |
2013-08-23 00:00:00.000 | 06.52.09 | 1 |
2013-08-23 00:00:00.000 | 06.57.39 | 1 |
2013-10-21 00:00:00.000 | 03.58.35 | 1 |
2013-10-21 00:00:00.000 | 04.02.18 | 1 |
2013-10-21 00:00:00.000 | 04.12.02 | 1 |
2013-10-21 00:00:00.000 | 04.41.36 | 1 |
2013-10-21 00:00:00.000 | 11.12.27 | 1 |
2013-10-22 00:00:00.000 | 11.58.35 | 1 |
I want to get the count of connect that fall in each hour, grouped by date.
Count falling between 1:00 to 1:59, 2:00 to 2:59 and so on. The below is model of the output that I require.
Date | Count(between 4.00.00 to 4.59.59) | Count(between 5.00.00 to 5.59.59) | Count(between 6.00.00 to 6.59.59) |Count(between 11.00.00 to 11.59.59) |
2013-08-23 00:00:00.000 | 0 | 3 | 5 | 0 |
2013-10-21 00:00:00.000 | 3 | 1 | 0 | 1 |
2013-10-22 00:00:00.000 | 0 | 0 | 0 | 1 |
You can just use group by with the date time functions if you don't care about missing 0 row counts, but if you are concerned, use the tally table example Jeff mentions in 2nd page of this forum post: http://www.sqlservercentral.com/Forums/Topic288581-8-1.aspx Both examples in this post, but it note it is by half hour, should be easy to convert to hour.
This is what I want.
by Matt Watson
SELECT [Hourly], COUNT(*) as [Count] FROM (SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly] FROM table) idat GROUP BY [Hourly]

Moving average in Temporal database in PostgreSQL

How can I apply the moving average in temporal database.
My data includes temperature and I want to apply moving average for every 15 records.
You can fire query as below
marc=# SELECT entity, name, salary, start_date,
avg(salary) OVER (ORDER BY entity, start_date
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM salary;
entity | name | salary | start_date | avg
-----------+-----------+---------+---------------+----------------------
Accounting | millicent | 850.00 | 2006-01-01 | 825.0000000000000000
Accounting | jack | 800.00 | 2010-05-01 | 916.6666666666666667
R&D | tom | 1100.00 | 2005-01-01 | 966.6666666666666667
R&D | john | 1000.00 | 2008-07-01 | 933.3333333333333333
R&D | maria | 700.00 | 2009-01-01 | 733.3333333333333333
R&D | kevin | 500.00 | 2009-05-01 | 633.3333333333333333
R&D | marc | 700.00 | 2010-02-15 | 600.0000000000000000
WITH moving_avrag AS (
SELECT 0 AS [lag] UNION ALL
SELECT 1 AS [lag] UNION ALL
SELECT 2 AS [lag] UNION ALL
SELECT 3 AS [lag] --ETC
)
SELECT
DATEADD(day,[lag],[date]) AS [reference_date],
[otherkey1],[otherkey2],[otherkey3],
AVG([value1]) AS [avg_value1],
AVG([value2]) AS [avg_value2]
FROM [data_table]
CROSS JOIN moving_avg
GROUP BY [otherkey1],[otherkey2],[otherkey3],DATEADD(day,[lag],[date])
ORDER BY [otherkey1],[otherkey2],[otherkey3],[reference_date];

How to use not in with conditions datetime

i need show datetime select only. But show all datetime in table filesTA.
this code:
SELECT *
FROM filesTA tf
WHERE NOT tf.EmpNo
IN (
SELECT lr.EmployeeRun
FROM LeaveRecord lr
WHERE lr.StartDate = '2012-10-01'
)
Output:
EmpNo | ChkDate | ChkIn | ChkOut
00001 | 2012-10-01 00:00:00.000 | 2012-10-01 07:21:00.000 | 2012-10-01 12:21:00.000
00002 | 2012-10-01 00:00:00.000 | 2012-10-01 08:13:00.000 | 2012-10-01 19:55:00.000
00003 | 2012-10-15 00:00:00.000 | 2012-10-15 07:06:00.000 | 2012-10-15 20:12:00.000
00004 | 2012-10-22 00:00:00.000 | 2012-10-22 07:12:00.000 | 2012-10-22 19:15:00.000
I need Output:
EmpNo | ChkDate | ChkIn | ChkOut
00001 | 2012-10-01 00:00:00.000 | 2012-10-01 07:21:00.000 | 2012-10-01 12:21:00.000
00002 | 2012-10-01 00:00:00.000 | 2012-10-01 08:13:00.000 | 2012-10-01 19:55:00.000
THANKS FOR YOUR TIME.
SELECT *
FROM filesTA tf
WHERE tf.EmpNo NOT
IN (
SELECT lr.EmployeeRun
FROM LeaveRecord lr
WHERE lr.StartDate = '2012-10-01'
)

Resources