Select top n after data operations SQL - azure-sql-database

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

Related

How to manipulate the output after selecting and ordering TOP RESULT

USE DNWorld
GO
SELECT TOP (100) WITH TIES PvPExp
FROM PvPRanking
ORDER BY PVPExp DESC
UPDATE PVPRanking
SET PVPLevel = 26
WHERE TOP(1) = 1
ERROR:
Msg 156, Level 15, State 1, Server NS544979, Procedure , Line 0
Incorrect syntax near the keyword 'TOP'.
[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near the keyword 'TOP'. (156)
I have successfully selected and ordered the PvPExp in the query.
I want to set PVPLEVEL = 26 for the #1 Top result. That isn't working.
Then from that I want to set The #2-#5 Top result a certain value.
So on and so forth. Please help
With RANK() window function:
WITH cte AS (
SELECT *, RANK() OVER (ORDER BY PVPExp DESC) AS rn
FROM PvPRanking
)
UPDATE cte
SET PVPLevel = CASE rn
WHEN 1 THEN 26
ELSE ?
END
WHERE rn <= 5
Replace ? with the value that you want to set to #2-#5 Top rows.
If you want to set different values for them also:
.............................
SET PVPLevel = CASE rn
WHEN 1 THEN 26
WHEN 2 THEN ?
WHEN 3 THEN ?
WHEN 4 THEN ?
WHEN 5 THEN ?
END
.............................
You can use row_number() with a CTE. ie:
with rankings (PvpExp, rowNo) as
(
SELECT PvPExp, row_number() over (order by PvpExp desc)
FROM PvPRanking
)
UPDATE PVPRanking
SET PVPLevel = case
when r.rowNo = 1 then 26
when r.rowNo > 1 and r.rowNo < 6 then xx
-- other settings
end
from PVPRanking pr
inner join rankings r on pr.PVPExp = r.PVPExp;
What you need might be Rank(), DenseRank() ... instead of row_number() based on your real needs.

SQL query to replace a string and convert rest of the string to Int

I have the below query. This query is supposed to look into my accounts table with my where parameter. That will return all account codes which start with leading 3 letters "DAG". The data return is consistently in the format leading with three letters followed by a number. I then want to get the most largest number. For that I order the string by converting it to Int.
I get this below error:
Msg 207, Level 16, State 1, Line 24
Invalid column name 'AccountCodeWithoutDAG '.
Here is my SQL query.
SELECT TOP 1
REPLACE(AccountCode, 'DAG', '') AS AccountCodeWithoutDAG
FROM
Accounts
WHERE
MangCode = 'ADFG'
ORDER BY
CONVERT(INT, AccountCodeWithoutDAG)
What am I doing wrong?
You can't use order by with convert alias
but you can try to use a subquery to get the AccountCodeWithoutDAG then order by it
SELECT TOP 1 AccountCodeWithoutDAG
FROM
(
SELECT REPLACE(AccountCode,'DAG','') AS AccountCodeWithoutDAG
FROM Accounts
where MangCode = 'ADFG'
) t1
Order by Convert(int, AccountCodeWithoutDAG )
As others have indicated, giving a calculated value an alias in the select does not give you the ability to use the same alias in subsequent clauses.
The way to do this nice-and-organized in sql server is cross apply:
SELECT TOP 1 AccountCodeWithoutDAG
FROM Accounts
cross apply (select REPLACE(AccountCode,'DAG','') AS AccountCodeWithoutDAG ) as calcquery
where
MangCode = 'ADFG'
Order by Convert(int, AccountCodeWithoutDAG )
The problem is the AccountCodeWithoutDAG, this is an alias and cannot be used in the order
Look what I did in testing below , use your replace statement in the convert part of the order by
declare #AccountCode varchar(100)='DAG123456'
SELECT top 1 REPLACE(#AccountCode,'DAG','') AS AccountCodeWithoutDAG
Order by Convert(int, REPLACE(#AccountCode,'DAG',''))

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;

Howto query average of most recent data in sqlserver

I want to find the average of the most recent x results. Is it possible to use an aggregate function on a limited number of results with sql server?
Here is what I have tried and the errors I get:
select avg(top(100) convert(float, AnalysisData))
from tab
order by DatePerformed desc
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword
'top'.
select AVG(data)
from (
select top(100) convert(float, AnalysisData) As data
from tab
order by DatePerformed desc
);
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near ')'.
This is sql server 2008
In your second example, you need an alias name for the subquery:
select AVG(data)
from (
select top 100 convert(float, AnalysisData) As data
from tab
order by DatePerformed desc
) Top100Records;
You probably don't need the parenthesis around 100 either.