Perform a Series of Calculations on a Multiple CTE Table - sql

Can't seem to figure out the formula for performing a series of functions on my query. I need to subtract the figures in the DIF column depending on the STAT code. I need to perform the same series of functions in every case. STAT I0099 MINUS E0002, this result will always be the denominator. After this I need to take each of the other lines in the table and divide them by this result.
1st (2811-98), 2nd E0013 (52/(2811-98)) 3rd E0019 (405/(2811-98)) 4th E0004 (2256/(2811-98) End.
I've tried adding rollup and a couple of others things, I saw on here, but none were successful.
WITH i_stat_cte
AS
(
SELECT ROW_NUMBER() OVER(partition by STAT Order by UDATE ) as
Rn,JCDS_SOGR.OBJNR, JCDS_SOGR.STAT,JCDS_SOGR.UDATE,JCDS_SOGR.CHGNR,JCDS_SOGR.CDTCODE,JCDS_SOGR.CHIND,JCDS_SOGR.INACT,JCDS_SOGR.TCODE,TJ02T.TXT30, EQUI.BAUJJ as "Year", T370K_T.EARTX as Model,
LAG(UDATE) OVER(partition by STAT Order by UDATE ) As PrevUDate,
COUNT(*) OVER(partition by STAT) As [Count]
from JCDS_SOGR
Join TJ02T on JCDS_SOGR.STAT = TJ02T.ISTAT
Join EQUI on JCDS_SOGR.OBJNR = EQUI.OBJNR
Join T370K_T on equi.EQART = T370K_T.EQART
where jcds_sogr.OBJNR = 'IE000000000010003137'
and TJ02T.SPRAS = 'E'
)
,
e_stat_cte
AS
(
SELECT ROW_NUMBER() OVER(partition by STAT Order by UDATE ) as Rn, JCDS_SOGR.OBJNR, JCDS_SOGR.STAT,JCDS_SOGR.UDATE,JCDS_SOGR.CHGNR,JCDS_SOGR.CDTCODE,JCDS_SOGR.CHIND,JCDS_SOGR.INACT,JCDS_SOGR.TCODE,TJ30T.TXT30, EQUI.BAUJJ as "Year", T370K_T.EARTX as Model,
LAG(UDATE) OVER(partition by STAT Order by UDATE ) As PrevUDate,
COUNT(*) OVER(partition by STAT) As [Count], TJ30T.MANDT as Client
from JCDS_SOGR
Join TJ30T on JCDS_SOGR.STAT = TJ30T.ESTAT
Join EQUI on JCDS_SOGR.OBJNR = EQUI.OBJNR
Join T370K_T on equi.EQART = T370K_T.EQART
where jcds_sogr.OBJNR = 'IE000000000010003137'
and TJ30T.SPRAS = 'E'AND TJ30T.MANDT='400'
AND TJ30T.STSMA = 'VEHICLE' AND T370K_T.MANDT = '400')
SELECT Max(rn) As [Count],
OBJNR,Year, Model, STAT,TXT30,
SUM(CASE WHEN rn%2=0 THEN DATEDIFF(d,PrevUDate,UDATE)
WHEN rn=[Count] THEN DATEDIFF(d,UDATE,getDate())
ELSE 0 END) as DIF
from i_stat_cte
Group BY OBJNR, STAT,TXT30, Year, Model
UNION
SELECT Max(rn) As [Count],
OBJNR,Year, Model, STAT,TXT30,
SUM(CASE WHEN rn%2=0 THEN DATEDIFF(d,PrevUDate,UDATE)
WHEN rn=[Count] THEN DATEDIFF(d,UDATE,getDate())
ELSE 0 END) as DIF
from e_stat_cte
Group BY OBJNR, STAT,TXT30, Year, Model
EXPECTED RESULTS
Count OBJNR Year Model STAT TXT30 DIF Avail | Calculations
1 IE000000000010003137 2011 Orion I0099 Avail 2810
2 IE000000000010003137 2011 Orion E0002 Await 98
4 IE000000000010003137 2011 Orion E0013 Non Op 52 .0191740 = (52/(2810-98))
4 IE000000000010003137 2011 Orion E0019 OperBk 405 .1493363 = (405/(2810-98))
7 IE000000000010003137 2011 Orion E0004 Oper 2255 .8314897 = (2255/(2810-98))

--The code below is a conversion of your code from CTE to temp tables.
--Hopefully you can perform better diagnostics on it. Just evaluate each of the data you are producing on your last query. I think the UNION is a bit sloppy. Are you sure it's really a UNION and not a UNION ALL?
DROP TABLE IF EXISTS #i_stat_cte
SELECT ROW_NUMBER() OVER(partition by STAT Order by UDATE ) as
Rn,JCDS_SOGR.OBJNR, JCDS_SOGR.STAT,JCDS_SOGR.UDATE,JCDS_SOGR.CHGNR,JCDS_SOGR.CDTCODE,JCDS_SOGR.CHIND,JCDS_SOGR.INACT,JCDS_SOGR.TCODE,TJ02T.TXT30, EQUI.BAUJJ as "Year", T370K_T.EARTX as Model,
LAG(UDATE) OVER(partition by STAT Order by UDATE ) As PrevUDate,
COUNT(*) OVER(partition by STAT) As [Count]
INTO #i_stat_cte
from JCDS_SOGR
Join TJ02T on JCDS_SOGR.STAT = TJ02T.ISTAT
Join EQUI on JCDS_SOGR.OBJNR = EQUI.OBJNR
Join T370K_T on equi.EQART = T370K_T.EQART
where jcds_sogr.OBJNR = 'IE000000000010003137'
and TJ02T.SPRAS = 'E'
DROP TABLE IF EXISTS #e_stat_cte
SELECT ROW_NUMBER() OVER(partition by STAT Order by UDATE ) as Rn, JCDS_SOGR.OBJNR, JCDS_SOGR.STAT,JCDS_SOGR.UDATE,JCDS_SOGR.CHGNR,JCDS_SOGR.CDTCODE,JCDS_SOGR.CHIND,JCDS_SOGR.INACT,JCDS_SOGR.TCODE,TJ30T.TXT30, EQUI.BAUJJ as "Year", T370K_T.EARTX as Model,
LAG(UDATE) OVER(partition by STAT Order by UDATE ) As PrevUDate,
COUNT(*) OVER(partition by STAT) As [Count], TJ30T.MANDT as Client
INTO #e_stat_cte
from JCDS_SOGR
Join TJ30T on JCDS_SOGR.STAT = TJ30T.ESTAT
Join EQUI on JCDS_SOGR.OBJNR = EQUI.OBJNR
Join T370K_T on equi.EQART = T370K_T.EQART
where jcds_sogr.OBJNR = 'IE000000000010003137'
and TJ30T.SPRAS = 'E'AND TJ30T.MANDT='400'
AND TJ30T.STSMA = 'VEHICLE' AND T370K_T.MANDT = '400'
-- VERIFY YOU GET WHAT YOU EXPECT
select * from #i_stat_cte
-- VERIFY YOU GET WHAT YOU EXPECT
select * from #e_stat_cte
-- VERIFY YOU GET WHAT YOU EXPECT
SELECT Max(rn) As [Count],
OBJNR,Year, Model, STAT,TXT30,
SUM(CASE WHEN rn%2=0 THEN DATEDIFF(d,PrevUDate,UDATE)
WHEN rn=[Count] THEN DATEDIFF(d,UDATE,getDate())
ELSE 0 END) as DIF
from #i_stat_cte
Group BY OBJNR, STAT,TXT30, Year, Model
--UNION
-- VERIFY YOU GET WHAT YOU EXPECT
SELECT Max(rn) As [Count],
OBJNR,Year, Model, STAT,TXT30,
SUM(CASE WHEN rn%2=0 THEN DATEDIFF(d,PrevUDate,UDATE)
WHEN rn=[Count] THEN DATEDIFF(d,UDATE,getDate())
ELSE 0 END) as DIF
from #e_stat_cte
Group BY OBJNR, STAT,TXT30, Year, Model

Related

Mandt Specified Multiple Times But Not in Query

I get this error
Msg 8156, Level 16, State 1, Line 67
The column 'MANDT' was specified multiple times for 'cte'."
when attempting to run the code below however I am not including the column MANDT in my query. Both tables that I am calling do have a column MANDT, but they both have the column STAT as well and I did not have a problem with another table attempting the same join, the only thing is that table did not have MANDT, only STAT was the same.
I attempted to include both columns MANDT with an alias: JCDS_SOGR.MANDT as Client and TJ30T.MANDT as Client2 separately and together, this did not pan out. Got the same error message.
;WITH cte AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY STAT ORDER BY UDATE) AS Rn,
*,
LAG(UDATE) OVER (PARTITION BY STAT ORDER BY UDATE) AS PrevUDate,
COUNT(*) OVER (PARTITION BY STAT) AS [Count]
FROM
JCDS_SOGR
JOIN
TJ30T on JCDS_SOGR.STAT = TJ30T.ESTAT
WHERE
OBJNR = 'IE000000000010003137'
)
SELECT
MAX(rn) AS [Count],
OBJNR, STAT, TXT30,
SUM(CASE
WHEN rn % 2 = 0
THEN DATEDIFF(d, PrevUDate, UDATE)
WHEN rn = [Count]
THEN DATEDIFF(d, UDATE, GETDATE())
ELSE 0
END) AS DIF
FROM
cte
GROUP BY
OBJNR, STAT, TXT30
This is the other query I referred to that works fine with this same code.
;with cte
AS
(
select ROW_NUMBER() OVER(partition by STAT Order by UDATE ) as Rn
, *
, LAG(UDATE) OVER(partition by STAT Order by UDATE ) As PrevUDate
, COUNT(*) OVER(partition by STAT) As [Count]
from JCDS_SOGR
join TJ02T on JCDS_SOGR.STAT = TJ02T.ISTAT
where OBJNR = 'IE000000000010003137'
and TJ02T.SPRAS = 'E'
)
select Max(rn) As [Count]
, OBJNR,STAT,TXT30
, SUM(CASE WHEN rn%2=0 THEN DATEDIFF(d,PrevUDate,UDATE)
WHEN rn=[Count] THEN DATEDIFF(d,UDATE,getDate())
ELSE 0 END) as DIF
from cte
group BY OBJNR, STAT,TXT30
The expected result is this
[COUNT OBJNR STAT TXT30 DIF
1 IE000000000010003137 I0099 Available 2810][1]
In your CTE, you are selecting *. So if you have two columns named MANDT, this could cause a conflict. Remove *. That should fix the problem that you described.

How to group data with conditions?

I'm trying to turn my current table using sql
customer.id sale_date
15 1/12/2017
15 2/12/2017
15 7/12/2017
12 6/09/2017
12 12/09/2017
16 8/14/2017
13 6/01/2017
13 7/01/2017
into something like this.
sale_date1 is the first order date.
sale_date2 is any order date one month after sale_date1.
sale_date3 is any order date five months after sale_date1.
customer.id sale_date1 sale_date2 sale_date3(at least 5 months after sale_date1)
15 1/12/2017 2/12/2017 7/12/2017
12 6/07/2017 NULL 12/09/2017
16 8/14/2017 NULL NULL
13 6/01/2017 7/01/2017 NULL
One option here would be to use correlated sub-queries to populate each of the three columns:
WITH cte AS (
SELECT [customer.id], MIN(sale_date) AS min_sale_date
FROM yourTable
GROUP BY [customer.id]
)
SELECT
[customer.id],
min_sale_date AS sale_date1,
(SELECT MIN(t2.sale_date) FROM yourTable t2
WHERE t1.[customer.id] = t2.[customer.id] AND
t2.sale_date >= DATEADD(month, 1, t1.min_sale_date) AND
t2.sale_date < DATEADD(month, 5, t1.min_sale_date)) AS sale_date2,
(SELECT MIN(t2.sale_date) FROM yourTable t2
WHERE t1.[customer.id] = t2.[customer.id] AND
t2.sale_date >= DATEADD(month, 5, t1.min_sale_date)) AS sale_date3
FROM cte t1
ORDER BY [customer.id];
Demo
Try below using row_number() and conditional aggregation
select customerid,max(case when seq=1 then sale_date end) as date1,
max(case when seq=2 then sale_date end) as date2,
max(case when seq=3 then sale_date end) as date3
from
(
select *, row_number() over(partition by customerid order by sale_date) as seq
from tablename
)X
group by customerid
I THINK THIS IS WHAT YOU WANT
SELECT A.customer.id, SALES1.sale_date , SALES2.sale_date ,SALES3.sale_date , SALES4.sale_date,SALES5.sale_date from
(SELECT distinct customer.id ,
From yourTable)A
LEFT JOIN
(SELECT * from
(SELECT customer.id, sale_date
ROW_NUMBER() OVER(ORDER BY sale_date ASC)
AS R1,
name, recovery_model_desc
FROM yourTable)S1 where R1=1)SALES1
A.customer.id = SALES1.customer.id
LEFT JOIN
(SELECT * from
(SELECT customer.id, sale_date
ROW_NUMBER() OVER(ORDER BY sale_date ASC)
AS R1,
name, recovery_model_desc
FROM yourTable)S1 where R1=2)SALES2
A.customer.id = SALES1.customer.id
LEFT JOIN
(SELECT * from
(SELECT customer.id, sale_date
ROW_NUMBER() OVER(ORDER BY sale_date ASC)
AS R1,
name, recovery_model_desc
FROM yourTable)S1 where R1=3)SALES3
A.customer.id = SALES1.customer.id
LEFT JOIN
(SELECT * from
(SELECT customer.id, sale_date
ROW_NUMBER() OVER(ORDER BY sale_date ASC)
AS R1,
name, recovery_model_desc
FROM yourTable)S1 where R1=2)SALES2
A.customer.id = SALES1.customer.id
LEFT JOIN
(SELECT * from
(SELECT customer.id, sale_date
ROW_NUMBER() OVER(ORDER BY sale_date ASC)
AS R1,
name, recovery_model_desc
FROM yourTable)S1 where R1=4)SALES4
A.customer.id = SALES1.customer.id
LEFT JOIN
(SELECT * from
(SELECT customer.id, sale_date
ROW_NUMBER() OVER(ORDER BY sale_date ASC)
AS R1,
name, recovery_model_desc
FROM yourTable)S1 where R1=2)SALES2
A.customer.id = SALES1.customer.id
LEFT JOIN
(SELECT * from
(SELECT customer.id, sale_date
ROW_NUMBER() OVER(ORDER BY sale_date ASC)
AS R1,
name, recovery_model_desc
FROM yourTable)S1 where R1=5)SALES5
A.customer.id = SALES1.customer.id
try this:
with mindate as (
select id, min(sale_date) MinDate,
DATEADD(month, 1, min(sale_date)) MinDatePlus1Month,
DATEADD(month, 5, min(sale_date)) MinDatePlus2Month
from yourtable
group by id
)
select f1.id, f1.MinDate sale_date1, f2.sale_date sale_date2, f3.sale_date sale_date3
from mindate f1
left outer join yourtable f2 on f1.id=f2.id and f1.MinDatePlus1Month=f2.sale_date
left outer join yourtable f3 on f1.id=f3.id and f1.MinDatePlus2Month=f3.sale_date

De-Dupe lines in CTE based off of one key in sql

I am not really sure on what I need with my issue. In the CTEs below I get an out put that gives me all the columns I want, but I am getting duplicates lines because a member can have two different type of Diagnosis code, What I want is to have one line per Member ID and then along with the DX codes so for example ...
MEMBERID FIRST_NAME BIRTHDATE DIAGNOSIS_CODE
999999999 John 9/9/9999 E11.9
999999999 John 9/9/9999 E79.8
I Want the output to be like this
MEMBERID FIRST_NAME BIRTHDATE DIAGNOSIS_CODE DIAGNOSIS_CODE
999999999 John 9/9/9999 E11.9 E79.8
See now its one line per member, this is my code below and it runs without any issues, I am just trying to get one line per member please. The example above are just for the example not actually in my code but thought it be easier to read the example, rather then my code. any help is greatly appreciated
WITH
Dates as ( Select ADD_MONTHS(TRUNC(sysdate,'MM'),-12) as MONTH1_BEGINDATE,
LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'),-1)) MONTH12_LASTDATE
from dual ---- requestor wants a rolling 12 month period
), --select * from Dates
DX AS (Select dx.diag_cd as Diagnosis_code, --- pulling in all members who have Diabetes DX regardless of date span from tab6 in ICUE for AZ
dx.mbr_id
From icue.mbr_diag dx
where dx.diag_cd in ('E08.00','E08.01','E08.10','E08.11','E08.21','E08.22','E08.29','E08.311','E08.319','E08.321',
'E08.329','E08.331','E08.339','E08.341','E08.349','E08.351','E08.352','E08.353','E08.354','E08.355',
'E08.359','E08.36','E08.37','E08.39','E08.40','E08.41','E08.42','E08.43','E08.44','E08.49',
'E08.51','E08.52','E08.59','E08.610','E08.618','E08.620','E08.621','E08.622','E08.628','E08.630',
'E08.638','E08.641','E08.649','E08.65','E08.69','E08.8','E08.9','E10.10','E10.11','E10.21',
'E10.22','E10.29','E10.311','E10.319','E10.321','E10.329','E10.331','E10.339','E10.341','E10.349',
'E10.351','E10.352','E10.353','E10.354','E10.355','E10.359','E10.36','E10.37','E10.39','E10.40',
'E10.41','E10.42','E10.43','E10.44','E10.49','E10.51','E10.52','E10.59','E10.610','E10.618',
'E10.620','E10.621','E10.622','E10.628','E10.630','E10.638','E10.641','E10.649','E10.65','E10.69',
'E10.8','E10.9','E11.00','E11.01','E11.10','E11.11','E11.21','E11.22','E11.29','E11.311',
'E11.319','E11.321','E11.329','E11.331','E11.339','E11.341','E11.349','E11.351','E11.352','E11.353',
'E11.354','E11.355','E11.359','E11.36','E11.37','E11.39','E11.40','E11.41','E11.42','E11.43',
'E11.44','E11.49','E11.51','E11.52','E11.59','E11.610','E11.618','E11.620','E11.621','E11.622',
'E11.628','E11.630','E11.638','E11.641','E11.649','E11.65','E11.69','E11.8', 'E11.9','E13.00',
'E13.01','E13.10','E13.11','E13.21','E13.22','E13.29','E13.311','E13.319','E13.321','E13.329',
'E13.331','E13.339','E13.341','E13.349','E13.351','E13.352','E13.353','E13.354','E13.355','E13.359',
'E13.36','E13.37','E13.39','E13.40','E13.41','E13.42','E13.43','E13.44','E13.49','E13.51',
'E13.52','E13.59','E13.610','E13.618','E13.620','E13.621','E13.622','E13.628','E13.630','E13.638',
'E13.641','E13.649','E13.65','E13.69','E13.8','E13.9') ---- all dx Diabetes code, pulling per request
), --select * From DX
members AS (
Select distinct -- need to dedup by member ID
max(case when d.mbr_id_typ_id = 2 then d.mbr_id_txt end) over (partition by d.mbr_id) as MemberID,
max(case when d.mbr_id_typ_id = 1 then d.mbr_id_txt end) over (partition by d.mbr_id) as SubscriberID,
max(case when d.mbr_id_typ_id = 3 then d.mbr_id_txt end) over (partition by d.mbr_id) as MemberAlternateID,
max(case when d.mbr_id_typ_id = 6 then d.mbr_id_txt end) over (partition by d.mbr_id) as MedicaidRecipientNumber,
mb.fst_nm as first_name,
mb.lst_nm as last_name,
trunc(mb.bth_dt) as birthdate,
dx.Diagnosis_code
from DX dx
inner join dates dd
on 1=1
inner join icue.mbr mb
on dx.mbr_id = mb.mbr_id
inner join icue.mbr_cov c -- pull in dates
on mb.mbr_id = c.mbr_id
inner join icue.mbr_id d -- member identifier
on dx.mbr_id = d.mbr_id
and d.mbr_id_typ_id in ('2','3','1','6')
and c.pol_iss_st_cd ='AZ' ---- Policy state lmiting to AZ only
and (c.lob_typ_id='12' OR c.clm_pltfm_id='A9') ---Community and state
), --select * from members
Members_with_diabetesDX AS (
Select m.*,dd.MONTH1_BEGINDATE, dd.MONTH12_LASTDATE from members m
inner join dates dd on 1=1
) select * from Members_with_diabetesDX
Thanks everyone for your help. I went ahead and used row_number then I criteria off of the Alias I did with ro_number . Below is my code.
WITH
Dates as ( Select ADD_MONTHS(TRUNC(sysdate,'MM'),-12) as MONTH1_BEGINDATE,
LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'),-1)) MONTH12_LASTDATE
from dual ---- requestor wants a rolling 12 month period
), --select * from Dates
DX AS (Select dx.diag_cd as Diagnosis_code, --- pulling in all members who have Diabetes DX regardless of date span from tab6 in ICUE for AZ
dx.mbr_id
From icue.mbr_diag dx
where dx.diag_cd in ('E08.00','E08.01','E08.10','E08.11','E08.21','E08.22','E08.29','E08.311','E08.319','E08.321',
'E08.329','E08.331','E08.339','E08.341','E08.349','E08.351','E08.352','E08.353','E08.354','E08.355',
'E08.359','E08.36','E08.37','E08.39','E08.40','E08.41','E08.42','E08.43','E08.44','E08.49',
'E08.51','E08.52','E08.59','E08.610','E08.618','E08.620','E08.621','E08.622','E08.628','E08.630',
'E08.638','E08.641','E08.649','E08.65','E08.69','E08.8','E08.9','E10.10','E10.11','E10.21',
'E10.22','E10.29','E10.311','E10.319','E10.321','E10.329','E10.331','E10.339','E10.341','E10.349',
'E10.351','E10.352','E10.353','E10.354','E10.355','E10.359','E10.36','E10.37','E10.39','E10.40',
'E10.41','E10.42','E10.43','E10.44','E10.49','E10.51','E10.52','E10.59','E10.610','E10.618',
'E10.620','E10.621','E10.622','E10.628','E10.630','E10.638','E10.641','E10.649','E10.65','E10.69',
'E10.8','E10.9','E11.00','E11.01','E11.10','E11.11','E11.21','E11.22','E11.29','E11.311',
'E11.319','E11.321','E11.329','E11.331','E11.339','E11.341','E11.349','E11.351','E11.352','E11.353',
'E11.354','E11.355','E11.359','E11.36','E11.37','E11.39','E11.40','E11.41','E11.42','E11.43',
'E11.44','E11.49','E11.51','E11.52','E11.59','E11.610','E11.618','E11.620','E11.621','E11.622',
'E11.628','E11.630','E11.638','E11.641','E11.649','E11.65','E11.69','E11.8', 'E11.9','E13.00',
'E13.01','E13.10','E13.11','E13.21','E13.22','E13.29','E13.311','E13.319','E13.321','E13.329',
'E13.331','E13.339','E13.341','E13.349','E13.351','E13.352','E13.353','E13.354','E13.355','E13.359',
'E13.36','E13.37','E13.39','E13.40','E13.41','E13.42','E13.43','E13.44','E13.49','E13.51',
'E13.52','E13.59','E13.610','E13.618','E13.620','E13.621','E13.622','E13.628','E13.630','E13.638',
'E13.641','E13.649','E13.65','E13.69','E13.8','E13.9') ---- all dx Diabetes code, pulling per request
), --select * From DX
members AS (
Select distinct -- need to dedup by member ID
max(case when d.mbr_id_typ_id = 2 then d.mbr_id_txt end) over (partition by d.mbr_id) as MemberID,
max(case when d.mbr_id_typ_id = 1 then d.mbr_id_txt end) over (partition by d.mbr_id) as SubscriberID,
max(case when d.mbr_id_typ_id = 3 then d.mbr_id_txt end) over (partition by d.mbr_id) as MemberAlternateID,
max(case when d.mbr_id_typ_id = 6 then d.mbr_id_txt end) over (partition by d.mbr_id) as MedicaidRecipientNumber,
mb.fst_nm as first_name,
mb.lst_nm as last_name,
trunc(mb.bth_dt) as birthdate,
dx.Diagnosis_code
from DX dx
inner join dates d
on 1=1
inner join icue.mbr mb
on dx.mbr_id = mb.mbr_id
--and mb.orig_sys_mbr_id in ('2','3')
inner join icue.mbr_cov c -- pull in dates
on mb.mbr_id = c.mbr_id
inner join icue.mbr_id d -- member identifier
on dx.mbr_id = d.mbr_id
and d.mbr_id_typ_id in ('2','3','1','6')
and c.pol_iss_st_cd ='AZ' ---- Policy state lmiting to AZ only
and (c.lob_typ_id='12' OR c.clm_pltfm_id='A9') ---Community and state
), --select * from members
Members_with_diabetesDX AS (
Select
m.MemberID,
m.SubscriberID,
m.MemberAlternateID,
m.MedicaidRecipientNumber,
m.first_name,
m.last_name,
m.birthdate,
m.Diagnosis_code,
row_number() over (partition by m.MemberID order by m.Diagnosis_code Desc) as Rank,
d.MONTH1_BEGINDATE,
d.MONTH12_LASTDATE
from members m
inner join dates d on 1=1
),-- select * from Members_with_diabetesDX
Final as (
Select
ff.MemberID,
ff.SubscriberID,
ff.MemberAlternateID,
ff.MedicaidRecipientNumber,
ff.first_name,
ff.last_name,
ff.birthdate,
max(case when ff.Rank = 1 then ff.Diagnosis_code end) over (partition by ff.MemberID) as firstdx,
max(case when ff.Rank = 2 then ff.Diagnosis_code end) over (partition by ff.MemberID) as secdx,
max(case when ff.Rank = 3 then ff.Diagnosis_code end) over (partition by ff.MemberID) as thirddx,
max(case when ff.Rank = 4 then ff.Diagnosis_code end) over (partition by ff.MemberID) as fourthdx,
ff.MONTH1_BEGINDATE,
ff.MONTH12_LASTDATE,
row_number() over (partition by ff.MemberID order by ff.Diagnosis_code,ff.SubscriberID,ff.MemberAlternateID,ff.MedicaidRecipientNumber,ff.first_name,ff.last_name,ff.birthdate Desc) as uniquerow
from Members_with_diabetesDX ff
) select * from Final where uniquerow ='1'

SQL query for Pricing analysis

Facing issue to find the Min and Max pricing status on the column YearMonth,
Below is my table data
YearMonth STATE ProductGroup LocaProdname Price
201407 MH AIRTEL AIRTEL-3G 10,000
201208 GJ IDEA IDEA-3G 1,200
201406 WB AIRCEL AIRCEL PERPAID 5,866
201407 DL TATA DOCOMA TATA LANDLINE 8,955
201207 KAR VODAFONE VODAFONE-3G 7,899
201312 MH AIRTEL AIRTEL-3G 15,000
201408 GJ IDEA IDEA-3G 25,000
I require below output:
YearMonth STATE ProductGroup LocaProdname Price Indictor-YEAR
201407 MH AIRTEL AIRTEL-3G 10,000 MAX
201312 MH AIRTEL AIRTEL-3G 15,000 MIN
201408 GJ IDEA IDEA-3G 25,000 MAX
201208 GJ IDEA IDEA-3G 1,200 MIN
I need the Max yearmonth and min Year values values.
If I understand correctly, you can do this with row_number():
select YearMonth, STATE, ProductGroup, LocaProdname, Price,
(case when seqnum_asc = 1 then 'MIN' else 'MAX' end) as Indicator
from (select d.*,
row_number() over (partition by state, productgroup, localprodname
order by price asc) as seqnum_asc,
row_number() over (partition by state, productgroup, localprodname
order by pricedesc) as seqnum_desc
from data
) d
where seqnum_asc = 1 or seqnum_desc = 1;
EDIT:
Does this do what you want?
select YearMonth, STATE, ProductGroup, LocaProdname, Price,
(case when seqnum_asc = 1 then 'MIN' else 'MAX' end) as Indicator
from (select d.*,
row_number() over (partition by YearMonth
order by price asc) as seqnum_asc,
row_number() over (partition by YearMOnth
order by pricedesc) as seqnum_desc
from data
) d
where seqnum_asc = 1 or seqnum_desc = 1;
Please use Row_number with partition BY and remove unwanted code as per your need,
SELECT yearmonth,state,productgroup,locaprodname,price,operation
FROM (
SELECT * FROM (SELECT p.yearmonth,p.state,p.productgroup,p.locaprodname,p.price,'MAX' AS Operation,
Row_number() OVER( partition BY p.productgroup, p.locaprodname
ORDER BY p.price DESC) AS Row
FROM pricingtest p) AS Maxx
WHERE Maxx.row = 1
UNION ALL
SELECT * FROM (SELECT p.yearmonth,p.state,p.productgroup,p.locaprodname,p.price,'MIN' AS Operation,
Row_number() OVER( partition BY p.productgroup, p.locaprodname
ORDER BY p.price ASC) AS Row
FROM pricingtest p) AS Minn
WHERE Minn.row = 1
) AS whole
ORDER BY yearmonth,productgroup
This can be done by finding the MAX/MIN values associated with the LocaProdname,ProductGroup and State then joining in on the table where everything matches. See below, or view the fiddle at http://sqlfiddle.com/#!3/4d6bd/2
NOTE: I've added in HAVING COUNT(*) > 1 as you seem to only want ones which have changed price. (Ie. Have more than 1 entry)
SELECT p.YearMonth
,p.State
,p.ProductGroup
,p.LocaProdname
,p.Price
,CASE
WHEN p.Price = a.MaxPrice
THEN 'MAX'
WHEN p.Price = a.MinPrice
THEN 'MIN'
END AS [Indicator-YEAR]
FROM PricingTest p
INNER JOIN (
SELECT LocaProdname
,ProductGroup
,State
,MAX(Price) AS MaxPrice
,MIN(Price) AS MinPrice
FROM pricingTest
GROUP BY LocaProdname
,ProductGroup
,State
HAVING COUNT(*) > 1
) a ON a.LocaProdname = p.LocaProdname
AND a.ProductGroup = p.ProductGroup
AND a.State= p.State
AND (
a.MaxPrice = p.Price
OR a.MinPrice = p.Price
)
ORDER BY LocaProdname
EDIT: Or I just noticed it's the max/min YearMonth the user might be looking, if this is the case check out http://sqlfiddle.com/#!3/4d6bd/4 It is basically just replacing all references to Price to YearMonth.
Once you get the last and first record you can UNION results:
SELECT t.*, 'MIN' AS Indicator
FROM
myTable t LEFT JOIN
myTable t2 ON t.YearMonth = t2.YearMonth AND t2.price < t.price
WHERE t2.YearMonth IS NULL
UNION
SELECT t.*, 'MAX' AS Indicator
FROM
myTable t LEFT JOIN
myTable t2 ON t.YearMonth = t2.YearMonth AND t2.price > t.price
WHERE t2.YearMonth IS NULL
If you have several records with same highest price, above query will return all of them. Also if you only have one record in a month, it will be returned twice as both MIN and MAX.

Selecting the Max Date From Multiple Tables

any help would be so incredibly appreciated. I am trying to select the last activity date from a group of tables. The tables include Entry Date, Note date, payment date, and Claim Date. I would like to return only the max value from all these dates. Furthermore I only want records where there has been no activity for over 45 days. I am currently using the following SQL to bring all the dates in then using calculated fields in EXCEL to figure the rest out. Is it possible to do this all with SQL?
Thanks in advance.
SELECT xrxTrnLgr.PatId, xrxTrnLgr.Balance,
Max(xrxPatNotes.NoteDate) AS 'Max of NoteDate',
Max(xrxTrnIcf.PostDate) AS 'Max of IcfPostDate',
Max(xrxPat.EntryDate) AS 'Entry Date',
Max(xrxPat.Coverage) AS 'Coverage',
Max(xrxTrnPay.PostDate) AS 'Last Payment'
FROM xrxTrnLgr
LEFT OUTER JOIN xrxPatNotes ON xrxTrnLgr.PatId = xrxPatNotes.PatId
LEFT OUTER JOIN xrxTrnIcf ON xrxTrnLgr.PatId = xrxTrnIcf.PatId
LEFT OUTER JOIN xrxPat ON xrxTrnLgr.PatId = xrxPat.PatId
LEFT OUTER JOIN xrxTrnPay ON xrxTrnLgr.PatId = xrxTrnPay.PatId
GROUP BY xrxTrnLgr.PatId, xrxTrnLgr.Balance
HAVING (xrxTrnLgr.Balance>$.01)
I think this might do it all in SQL:
select t.patid, t.balance,
max(case when which = 'note' then thedate end) as note,
max(case when which = 'post' then thedate end) as post,
max(case when which = 'entry' then thedate end) as entry,
max(case when which = 'coverage' then thedate end) as coverage,
max(case when which = 'lastPayment' then thedate end) as lastPayment
from xrxTrnLgr t left join
((select patid, notedate as thedate, 'note' as which
from xrxPatNotes
) union all
(select patid, postdate, 'post'
from xrxtrnIcf
) union all
(select patid, EntryDate, 'entry'
from xrxPat
) union all
(select paid, Coverage, 'coverage'
from xrxPat.Coverage
) union all
(select patid, PostDate, 'LastPayment'
from xrxTrnPay.PostDate
)
) d
on t.patid = d.patid
group by t.patid, t.balance
having min(now() - thedate) >= 45