I have gone through the particular posts but couldn't still fix the issue I having with Inner Join of two SQL statements with a Row_number function call in them.
Trying to pull data from two tables. I am using Row_Number to get the distinct policies as there are lots of duplicate values. I can't figure out what is wrong in the Inner Join part.
Select *
from
(Select Distinct
PolicyReference as IRIS_Policy_Ref ,
REPLACE(SUBSTRING(Ch.ClaimSuffix,3,4),'-','') as Claims_Seq,
CH.AccidentDate as Loss_Date,
CH.AccidentYear as Loss_Year,
CH.ClaimCreatedDate as Claim_Advised_Date,
CH.NoticeDescription as Loss_Description,
NULL as Conv_Claim_No,
NULL as CHI,
NULL as Manual,
BrokerRef as Broker_Code,
Null as Current_ACR,
Null as Current_IBNR,
Source ='DCT',
ROW_NUMBER() OVER(PARTITION BY PolicyReference ORDER BY TransactionDate DESC) RowNum
from
dbo.Policy) PM
INNER JOIN
dbo.Claims CH ON Ch.PolicyReference = PM.PolicyReference
where
PM.RowNum = 1
Error message sample -
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "Ch.ClaimSuffix" could not be bound.
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "Ch.AccidentDate" could not be bound.
Msg 4104, Level 16, State 1, Line 5
The multi-part identifier "CH.AccidentYear" could not be bound.
What am I doing wrong? It is not recognizing the claims table columns.
Any leads would be greatly appreciated. I am stuck in this since morning.
Thanks !!
You can't reference Claims in your subquery like that because it hasn't been introduced. Why not move that join to the primary query like this?
Select *
from
(
Select
PolicyReference as IRIS_Policy_Ref ,
REPLACE(SUBSTRING(Ch.ClaimSuffix,3,4),'-','') as Claims_Seq,
CH.AccidentDate as Loss_Date,
CH.AccidentYear as Loss_Year,
CH.ClaimCreatedDate as Claim_Advised_Date,
CH.NoticeDescription as Loss_Description,
NULL as Conv_Claim_No,
NULL as CHI,
NULL as Manual,
BrokerRef as Broker_Code,
Null as Current_ACR,
Null as Current_IBNR,
Source ='DCT',
ROW_NUMBER() OVER(PARTITION BY PolicyReference ORDER BY TransactionDate DESC) RowNum
from dbo.Policy P
INNER JOIN dbo.Claims CH ON Ch.PolicyReference = P.PolicyReference
) PM
where PM.RowNum = 1
Many people like to use CTEs:
with table_with_rowsnums as (
Select * from (Select Distinct
PolicyReference as IRIS_Policy_Ref ,
REPLACE(SUBSTRING(Ch.ClaimSuffix,3,4),'-','') as Claims_Seq,
CH.AccidentDate as Loss_Date,
CH.AccidentYear as Loss_Year,
CH.ClaimCreatedDate as Claim_Advised_Date,
CH.NoticeDescription as Loss_Description,
NULL as Conv_Claim_No,
NULL as CHI,
NULL as Manual,
BrokerRef as Broker_Code,
Null as Current_ACR,
Null as Current_IBNR,
Source ='DCT',
ROW_NUMBER() OVER(PARTITION BY PolicyReference ORDER BY TransactionDate
DESC) RowNum
from dbo.Policy ) PM
INNER JOIN dbo.Claims CH ON Ch.PolicyReference = PM.PolicyReference)
select * from table_with_rowsnums where rownum=1
There is no need to use select distinct with row_number(). In addition, CH has no reference. You need to do the JOIN in the subquery:
select *
from (Select pm.PolicyReference as IRIS_Policy_Ref ,
REPLACE(SUBSTRING(Ch.ClaimSuffix, 3, 4), '-', '') as Claims_Seq,
CH.AccidentDate as Loss_Date,
CH.AccidentYear as Loss_Year,
CH.ClaimCreatedDate as Claim_Advised_Date,
CH.NoticeDescription as Loss_Description,
NULL as Conv_Claim_No,
NULL as CHI,
NULL as Manual,
BrokerRef as Broker_Code,
Null as Current_ACR,
Null as Current_IBNR,
Source ='DCT',
ROW_NUMBER() OVER (PARTITION BY pm.PolicyReference ORDER BY pm.TransactionDate DESC) RowNum
from dbo.Policy p JOIN
dbo.Claims CH
ON Ch.PolicyReference = PM.PolicyReference
) PM
where PM.RowNum = 1 ;
Related
I have a CTE that basically filters data based on certain criteria, the thing is that after filtering I need to update these records to "correct" them but I get a 4104 on the UPDATE statement.
When I call directly the variable I don't have problems but where I do a calculation I get an error because I'm calling the variables from the first and second query.
;WITH CTE AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY timestmp ASC) order,
*
FROM TSTSOLAP T
(
--SECOND QUERY
SELECT 1 FROM TABLE1 T2
WHERE --CONDITIONS MET
t.user_id = t2.id_user AND
T.ID_TIP = T2.ID_TIP AND
T.ID <> t2.ID AND
(T2.BEG BETWEEN T.BEG AND T.END)
OR T2.BEG = T.END
)
)
UPDATE CTE SET STAT=0, END = (T2.END - 1) --HERE IS WHERE I GET THE: Msg 4104, Level 16, State 1, Line 1
WHERE ORDER> 1
GO
How could I call the non-linked variables?
*Code shortened because lenght
How about just doing a JOIN?
WITH toupdate AS (
SELECT . . . ,
? as order
FROM table1
)
UPDATE T
SET STAT = 0,
END = (T2.END - 1)
FROM T JOIN
table2 T2
ON . . . <conditions here>
WHERE T.ORDER > 1;
Depending on what your conditions are in the subquery, you might still need the EXISTS clause as well.
My UPDATE statement here:
Update S
set Status = 6
Where Status = 5
and P_ID in (1, 3)
and ID in (Select dbo.T.sID
from dbo.T
Group By s
having Max(TDate) <= #t1 and Max(TDate) >= #t2
and sid is not null
order by Max(TDate))
results in an error being shown:
Msg 1033, Level 15, State 1, Line 6
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
order by clause meaningless for inline queries. Just delete order by Max(TDate) part from your query.
Update S
set Status = 6
Where Status = 5
and P_ID in (1, 3)
and ID in (Select dbo.T.sID
from dbo.T
Group By s
having Max(TDate) <= #t1 and Max(TDate) >= #t2
and sid is not null )
I am trying to add Percentile value for each record as new column. But i am getting error in my SQL query. Can anyone please help to solve it.
Error message:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'inner'.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near 'a'.
Select b.* , a.[Rank_1]/count(b.[Date]) * 100 as Percentile from
[Country_table1$] b where [Country] = 'AUSTRALIA'
inner join
(
select [MSCI_Price_idx], [Country], rank() OVER (PARTITION BY [Country]
ORDER BY [MSCI_Price_idx] DESC) AS [Rank_1]
from [Country_table1$]
GROUP BY [MSCI_Price_idx],[Country]
) a
ON a.[Country] = b.[Country]
You have your where statement in the wrong place. Joins are formally part of the from statement and thus come before criteria. To have your criterion at the bottom check the correct table you use the alias.
Select b.* , a.[Rank_1]/count(b.[Date]) * 100 as Percentile from
[Country_table1$] b
inner join
(
select [MSCI_Price_idx], [Country], rank() OVER (PARTITION BY [Country]
ORDER BY [MSCI_Price_idx] DESC) AS [Rank_1]
from [Country_table1$]
GROUP BY [MSCI_Price_idx],[Country]
) a
ON a.[Country] = b.[Country]
where b.[Country] = 'AUSTRALIA'
What am I doing wrong here?
The result is an error, saying:
Msg 102, Level 15, State 1, Line 3 Incorrect syntax near 'order'.
Msg 156, Level 15, State 1, Line 25 Incorrect syntax near the keyword
'as'.
select *
, Antal + Normtid as Flextid
, SUM(antal) OVER (PARTITION BY transdate ORDER BY tekst)
, x = row_number() over (partition by åruge order by tekst)
from
(
select *
,
(
select b.antal
from bi.dbo.Table_pg_FlextidsopgørelseGlUdgave b
where b.tekst = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.tekst
and b.transdate = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.transdate
and b.åruge = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.åruge
and b.type = 'Normtid'
) as Normtid
from
bi.dbo.Table_pg_FlextidsopgørelseGlUdgave
where type = 'afholdt'
and tekst = 'fs'
--and åruge = '201501'
) as data
order by tekst, transdate
Regards
Peter
It is obvious that you have inappropriate version of Sql Server. Cumulative sums with order by clause like:
SUM(antal) OVER (PARTITION BY transdate ORDER BY tekst)
are only available from Sql Server 2012+.
Actually I can reproduce those errors on Sql Server 2008:
This is on Sql Server 2012:
Notice how the error message changes.
The way you are getting data from derived table is not correct..
EX:
create table
sales
(
id int
)
insert into sales
values
(1),
(2),
(3)
derived table should always have table alias and parent table should refer using from
----this is valid
select
* from
(
select id+1 as id1
from sales
) b
--this is not valid
select
*
(select
id from sales
)b
--Above is valid when you have a subquery say
select
id,(select t1.name from table t1 where t1.id=t2.id)as custname
from table t2
coming to your question..this is not valid.I see both table types are same
select *
,
(
select b.antal
from bi.dbo.Table_pg_FlextidsopgørelseGlUdgave b
where b.tekst = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.tekst
and b.transdate = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.transdate
and b.åruge = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.åruge
and b.type = 'Normtid'
) as Normtid
from
bi.dbo.Table_pg_FlextidsopgørelseGlUdgave
where type = 'afholdt'
and tekst = 'fs'
--and åruge = '201501'
So you can write something like below
select *
, Antal + Normtid as Flextid
, SUM(antal) OVER (PARTITION BY transdate ORDER BY tekst)
, x = row_number() over (partition by åruge order by tekst)
from
(
select * from
(
select b.antal
from bi.dbo.Table_pg_FlextidsopgørelseGlUdgave b
where b.tekst = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.tekst
and b.transdate = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.transdate
and b.åruge = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.åruge
and b.type = 'Normtid'
and b.type='afholdt'
and b.tekst = 'fs'
) as Normtid
order by tekst, transdate
I have a table with data and one of the columns contains a number stored as text.
When an application updates it, it writes _BAK + datetime stamp behind the number.
I'm now trying to clean up the database by deleting all records that have _BAK in the number column where the most recent one must not be deleted.
id sitenummer
28376 1441_BAK20130213151952032
28377 1441_BAK20130214142314705
In this case the line with ID 28376 is the oldest and must be removed.
I have created a query that should do just that:
;with sel1 AS (
select t1.ID,t1.sitenummer, CONVERT(BIGint,SUBSTRING(t1.sitenummer,CHARINDEX('_',t1.sitenummer,0)+4,50)) as Stamp1
from vdfkraan as t1
where t1.sitenummer like '%_BAK%' and (SELECT COUNT(SUBSTRING(t2.sitenummer,0,CHARINDEX('_',t2.sitenummer,0))) FROM vdfkraan as t2
where SUBSTRING(t1.sitenummer,0,CHARINDEX('_',t1.sitenummer,0))=SUBSTRING(t2.sitenummer,0,CHARINDEX('_',t2.sitenummer,0))) > 1
group by t1.id,t1.sitenummer)
, sel2 AS (
select t3.id, t3.sitenummer, t3.stamp1,
(select TOP(1) t4.stamp1 from sel1 as t4
WHERE SUBSTRING(t4.sitenummer,0,CHARINDEX('_',t4.sitenummer,0)) =SUBSTRING(t3.sitenummer,0,CHARINDEX('_',t3.sitenummer,0))
order by t3.Stamp1 DESC) AS stamp2 from sel1 as t3)
, sel3 AS (select id from sel2 where Stamp1=stamp2)
--delete FROM vdfkraan
--where id IN (SELECT t1.id FROM sel3 as t1)
--select * from sel2
If I uncomment the last line (select * from sel2), it produces the following table:
id sitenummer stamp1 stamp2
28376 1441_BAK20130213151952032 20130213151952032 20130213151952032
28377 1441_BAK20130214142314705 20130214142314705 20130213151952032
Table sel3 contains one record with one column id = 28376.
So that seems to work just as I want it.
Now I comment the select line and uncomment the Delete lines.
Now I get the following error:
Msg 8114, Level 16, State 5, Line 2
Error converting data type varchar to bigint.
So without the delete lines, all is ok, no errors, but with it, I get this error.
I have checked the data, there should not be any problem.
What is going on here?
Try with this:
SELECT v.ID
, v.sitenummer
, ROW_NUMBER() OVER (PARTITION BY LEFT(v.sitenummer, PATINDEX('%_BAK%', v.sitenummer) - 1) ORDER BY v.id DESC) num
INTO #temp
FROM vdfkraan v
WHERE PATINDEX('%_BAK%', v.sitenummer) > 0
DELETE vdfkraan
FROM #temp t
JOIN vdfkraan v ON v.id = t.id
AND t.num <> 1
SELECT *
FROM vdfkraan
Here is an SQL Fiddle
I think you can use grouping instead of window function:
SELECT max(id), max(sitenummer)
FROM vdfkraan
group by left(sitenummer,charindex('_BAK',sitenummer));