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

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

Related

SQL Error: Incorrect syntax near the keyword 'FROM'

This is my SQL query that is throwing a syntax error around/ near the 'FROM' portion. Any help would be awesome!
with findlives AS
(
select distinct a.ClientId, a.PolicyNo, a.Acc, a.Lives, a.FundTypeCmr
from factInforceProfitByFundGb as a
where TimePeriodId = 202006
and BenefitCode='66'
and TerminationDate = '9999-12-31'
)
select sum(Lives) AS spousal
from findlives
from [GB_Msi_P1].[dbo].[factInforceProfitByFundGb] as a
where TimePeriodId >= 201811
and BenefitCode in ('25', '26', '29', '46', '66')
group by TimePeriodId
order by TimePeriodId asc
Here is the error;
Msg 156, Level 15, State 1, Line 22
Incorrect syntax near the keyword 'FROM'
As said in comments by the-impaler, you can only have one FROM clause per SELECT. Multiple tables need to be JOINed together, or (deprecated) chained with commas.
Perhaps you're trying to join the CTE with the table it's based on, but you want type 66 records from the CTE and match them to other type records from the table? In that case you do want a JOIN. Perhaps this one?
with findlives AS
(
select distinct aaa.ClientId, aaa.PolicyNo, aaa.Acc, aaa.Lives, aaa.FundTypeCmr
from factInforceProfitByFundGb as aaa
where TimePeriodId = 202006
and BenefitCode='66'
and TerminationDate = '9999-12-31'
)
select a.TimePeriodId,sum(findlives.Lives) AS spousal
from findlives
JOIN [GB_Msi_P1].[dbo].[factInforceProfitByFundGb] as a
ON findlives.ClientID=a.clientID
where a.TimePeriodId >= 201811
and a.BenefitCode in ('25', '26', '29', '46', '66')
group by a.TimePeriodId
order by a.TimePeriodId asc
I've also added additonal table aliases to make things clear, and added a.TimePeriodId to the SELECT because otherwise your output isn't going to be clear (which output row goes with which group member?)

Error in SQL Server query - inner join

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'

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 ))

Select From CTE using AS? SQL Server 2008

I'm trying to convert a PostgreSQL into SQL Server. But this query doesn't work.
What am I doing wrong? I tried to add a semicolon before WITH but no luck.
SELECT
member_a AS you, member_b AS mightknow, shared_connection,
CASE
WHEN (n1.member_job_country = n2.member_job_country AND n1.member_job_country = n3.member_job_country) THEN 'country in common'
WHEN (n1.member_unvan_id = n2.member_unvan_id AND n1.member_unvan_id = n3.member_unvan_id) THEN 'unvan in common'
ELSE 'nothing in common'
END AS reason
FROM (
WITH transitive_closure(member_a, member_b, distance, path_string, direct_connection) AS
(SELECT
member_a, member_b, 1 AS distance,
CAST(member_a as varchar(MAX)) + '.' + CAST(member_b as varchar(MAX)) + '.' AS path_string,
member_b AS direct_connection
FROM Member_Contact_Edges
WHERE member_a = 45046 -- set the starting node
UNION ALL
SELECT
tc.member_a, e.member_b, tc.distance + 1,
CAST(tc.path_string as varchar(MAX)) + CAST(e.member_b as varchar(MAX)) + '.' AS path_string,
tc.direct_connection
FROM Member_Contact_Edges AS e
JOIN transitive_closure AS tc ON e.member_a = tc.member_b
WHERE tc.path_string NOT LIKE '%' + CAST(e.member_b as varchar(MAX)) + '.%'
AND tc.distance < 2
)
SELECT
member_a, member_b,direct_connection AS shared_connection
FROM transitive_closure
WHERE distance = 2
) AS youmightknow
LEFT JOIN Members AS n1 ON youmightknow.member_a = n1.memberID
LEFT JOIN Members AS n2 ON youmightknow.member_b = n2.memberID
LEFT JOIN Members AS n3 ON youmightknow.shared_connection = n3.memberID
WHERE (n1.member_job_country = n2.member_job_country
AND n1.member_job_country = n3.member_job_country)
OR (n1.member_unvan_id = n2.member_unvan_id
AND n1.member_unvan_id = n3.member_unvan_id);
Error I get:
Msg 156, Level 15, State 1, Line 11
Incorrect syntax near the keyword 'WITH'.
Msg 319, Level 15, State 1, Line 11
Incorrect syntax near the keyword 'with'. If this statement is a
common table expression, an
xmlnamespaces clause or a change
tracking context clause, the previous
statement must be terminated with a
semicolon.
Msg 102, Level 15, State 1, Line 34
Incorrect syntax near ')'.
Here is the reference; Graphs in the Database - SQL Meets Social Networks - Look at the facebook suggestion part at the bottom of the article.
Thanks in advance
The CTE declaration needs to go at the top. You can also have multiple CTEs declared and joined by commas rather than mixing CTEs and derived tables.
Try
;WITH
/*First CTE declaration*/
transitive_closure(member_a, member_b, distance, path_string, direct_connection)
AS
(
...
),
/*Second CTE declaration*/
youmightknow AS
(
SELECT member_a, member_b,direct_connection AS shared_connection
FROM transitive_closure
WHERE distance = 2
)
SELECT member_a AS you,
...
FROM youmightknow
Move your CTE definition to the beginning of your SQL statement. The keyword WITH appears once at the beginning of your statement to introduce one or more CTEs, which may then be referred to in the following SQL. Take a look at this CTE example, it will clear it up for you.