Error in SQL Server query - inner join - sql

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'

Related

SQL Max from Subquery, Msg 102, Incorrect syntax near ')'

I'm trying to get only the Max-Results of the sums per day. I'm trying this with
Select Max(Anzahl) from (Subquery)
The Subquery itself works, but when I put it into the brackets, I get the following error message:
Msg 102, Level 15, State 1, Line 8 Incorrect syntax near ')'.
See below for the whole query.
Many thanks for any hints!
Cheers
Lukas
select Max(Anzahl) from
(
select CONVERT(VARCHAR(10), log1.timestamp, 104) as Date, log1.ID, count(*) Anzahl
from log1
inner join base on log1.ID = base.ID
where abc like '%test%' and log1.xyz = 3
GROUP BY CONVERT(VARCHAR(10), log1.timestamp, 104), log1.ID
)
In SQL every derived table requires an alias so it can be uniquely identified, so
select Max(Anzahl) from
(
select CONVERT(VARCHAR(10), log1.timestamp, 104) as Date, log1.ID, count(*) Anzahl
from log1
inner join base on log1.ID = base.ID
where abc like '%test%' and log1.xyz = 3
GROUP BY CONVERT(VARCHAR(10), log1.timestamp, 104), log1.ID
) as AliasName

Select top n after data operations SQL

I want to
Filter a data set
Take distinct of a column
take out top 10 rows of that data set with the distinct column
The code I am using is
SELECT TOP (10) *
FROM (
SELECT DISTINCT(business_id) FROM businessdata
WHERE businessdata.city = 'Phoenix'
)
;
and the error I am getting is
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near ';'.
Where am I going wrong?
You have to give a name to the subquery:
SELECT TOP (10) *
FROM (
SELECT DISTINCT(business_id) FROM businessdata
WHERE businessdata.city = 'Phoenix'
) AS my_subquery
ORDER BY businessdata
;
make sure you also an ORDER BY to correctly set the order and thus make TOP meaningful

Inner Join between 2 sql having ROW_Number SQL Server

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 ;

SELECT query using group by

I don't know why the following query is not working:
SELECT whs_code, pdt_code,case_dt_yyyymmdd, fresh_frozen_status,
SUM(qty_cases_on_hand)-Qty, SUM(qty_weight_on_hand)-Wt, operation
FROM
(
SELECT whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation,SUM(qty_cases_on_hand) AS Qty, SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='RU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
)
WHERE operation='SU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation`
The error is :
Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'WHERE'.
To make it simple to understand what i am trying to do here, please see the example
I need data as result of
(SELECT x FROM tbl_table Where column y='SU')-(SELECT x FROM tbl_table Where column y='RU')
SELECT ru.whs_code,
ru.pdt_code,
ru.case_dt_yyyymmdd,
ru.fresh_frozen_status,
ru.operation,
ru.Qty - su.Qty AS Qty_Diff,
ru.Wt - su.Wt AS Wt_Diff
FROM
(
SELECT whs_code,
pdt_code,
case_dt_yyyymmdd,
fresh_frozen_status,
operation,
SUM(qty_cases_on_hand) AS Qty,
SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='RU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
) ru,
(
SELECT whs_code,
pdt_code,
case_dt_yyyymmdd,
fresh_frozen_status,
operation,
SUM(qty_cases_on_hand) AS Qty,
SUM(qty_weight_on_hand) AS Wt
FROM tbl_inventory_activity_rpt1
WHERE operation ='SU'
GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation
) su
WHERE ru.whs_code = su.whs_code
AND ru.pdt_code = su.pdt_code
AND ru.case_dt_yyyymmdd = su.case_dt_yyyymmdd
AND ru.fresh_frozen_status = su.fresh_frozen_status
AND ru.operation = su.operation;

Works in SQLFiddle Not in SQL Server 2012

When I run this Query in SQL Fiddle it runs perfectly:
;with cte as
(SELECT
analysisvalue.analysisid,
heatname,
analysistime,
sampletype,
grade,
productid,
element,
value
FROM
dbo.AnalysisValue
INNER JOIN
dbo.CAnalysis
ON
dbo.AnalysisValue.AnalysisID = dbo.CAnalysis.AnalysisID
WHERE
heatname = 'A7M0066'
)
SELECT
*
FROM
S_analysis s
CROSS JOIN (SELECT TOP 1 analysistime
FROM cte
ORDER BY analysisid desc
) c
WHERE s.heat_no = 'A7M0066' OR
(s.analysis_datetime BETWEEN c.analysistime AND DATEADD(hh, 2, c.analysistime ))
However when I run it in SQL Server 2012, I receive this error with the leading semi-colon:
Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near ';'.
And this error when without the semicolon:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'with'.
Instead of a CTE, you could use a #temp table and see if the query is valid:
SELECT
analysisvalue.analysisid,
heatname,
analysistime,
sampletype,
grade,
productid,
element,
value
INTO #temptable
FROM
dbo.AnalysisValue
INNER JOIN
dbo.CAnalysis
ON
dbo.AnalysisValue.AnalysisID = dbo.CAnalysis.AnalysisID
WHERE
heatname = 'A7M0066';
SELECT *
FROM
S_analysis s
CROSS JOIN (SELECT TOP 1 analysistime
FROM #temptable
ORDER BY analysisid desc
) c
WHERE s.heat_no = 'A7M0066' OR
(s.analysis_datetime BETWEEN c.analysistime AND DATEADD(hh, 2, c.analysistime ))