SQL Server 2008 merging the result of two queries - sql

I am trying to merge the result of both the queries below using the UNION operator in SQL Server 2008 but got the following error
Incorrect syntax near the keyword 'union'.
My code:
SELECT TOP 1
CITY, LEN(CITY)
FROM
table1
ORDER BY
LEN (CITY), CITY ASC
UNION
SELECT TOP 1
CITY, LEN(CITY)
FROM
table1
ORDER BY
LEN (CITY) DESC, CITY ASC
Any comments would be appreciated.
Thanks

Here is the correct way to do it
Select * From
(
SELECT TOP 1
CITY, cityLen = LEN(CITY)
FROM
table1
ORDER BY
cityLen, CITY ASC
) a
UNION
Select * From
(
SELECT TOP 1
CITY, cityLen = LEN(CITY)
FROM
table1
ORDER BY
cityLen DESC, CITY ASC
) b
or using Row_Number window function
select * from
(
select *,
ROW_NUMBER() OVER(ORDER BY LEN (CITY) DESC, CITY ASC) as Drn,
ROW_NUMBER() OVER(ORDER BY LEN (CITY) ASC, CITY ASC) as Arn,
FROM table1
) a
where 1 in (Arn,Drn)

In this case, you can use Common table expression. Try this
;With cte
AS (
select * , ROW_NUMBER() OVER(ORDER BY LEN (CITY) DESC, CITY ASC) as rn
FROM table1
)
select * from cte where rn = 1
union
select * from cte where rn = 1

Remove the ASC order command in your first select statement. You can only order the result at the end of any query as ordering in the middle of a query (if allowed) would cause many problems in getting consistent results.
EDIT: I realized the table were the same, you need to use Union ALL, or as stated in other comments, the duplicates are taken out in a UNION.
SELECT TOP 1
CITY, LEN(CITY)
FROM
table1
UNION ALL
SELECT TOP 1
CITY, LEN(CITY)
FROM
table1
ORDER BY
LEN (CITY) DESC, CITY ASC

Related

Replacement for row_number() in clickhouse

Row_number () is not supported by clickhouse database, looking for a alternate function.
SELECT company_name AS company,
DOMAIN,
city_name AS city,
state_province_code AS state,
country_code AS country,
location_revenue AS revenueRange,
location_TI_industry AS industry,
location_employeecount_range AS employeeSize,
topic,
location_duns AS duns,
rank AS intensityRank,
dnb_status_code AS locationStatus,
rank_delta AS intensityRankDelta,
company_id,
ROW_NUMBER() OVER (PARTITION BY DOMAIN) AS rowNumberFROM company_intent c
WHERE c.rank > 0
AND c.rank <= 10
AND c.signal_count > 0
AND c.topic IN ('Cloud Computing')
AND c.country_code = 'US'
AND c.rank IN (7, 8, 9, 10)
GROUP BY c.location_duns,
company_name,
DOMAIN,
city_name,
state_province_code,
country_code,
location_revenue,
location_TI_industry,
location_employeecount_range,
topic,
rank,
dnb_status_code,
rank_delta,
company_id
ORDER BY intensityRank DESC
LIMIT 15 SELECT COUNT (DISTINCT c.company_id) AS COUNT
FROM company_intent c
WHERE c.rank > 0
AND c.rank <= 10
AND c.signal_count > 0
AND c.topic IN ('Cloud Computing')
AND c.country_code = 'US'
AND c.rank IN (7, 8, 9, 10)
When executed the above query got the below error.
Expected one of: SETTINGS, FORMAT, WITH, HAVING, LIMIT, FROM, PREWHERE, token, UNION ALL, Comma, WHERE, ORDER BY, INTO OUTFILE, GROUP BY
any suggestions is appreciated
Solution #1
SELECT
*,
rowNumberInAllBlocks()
FROM
(
-- YOUR SELECT HERE
)
https://clickhouse.com/docs/en/sql-reference/functions/other-functions/#rownumberinallblocks says:
rowNumberInAllBlocks() Returns the ordinal number of the row in the data block. This function only considers the affected data blocks.
Solution #2
SELECT
row_number() OVER (),
...
FROM
...
https://clickhouse.com/docs/en/sql-reference/window-functions/
In my tests, both solutions show identical results. However, you need to remember that at the beginning of 2022, window functions work in single-threaded mode.
ClickHouse doesn't support Window Functions for now. There is a rowNumberInAllBlocks function that might be interesting to you.
SELECT *, rowNumberInAllBlocks() as row_count FROM (SELECT .....)
smth like this (terrible lokks but works good)
SELECT *, rn +1 -min_rn current, max_rn - min_rn + 1 last FROM (
SELECT *, rowNumberInAllBlocks() rn FROM (
SELECT i_device, i_time
FROM tbl
ORDER BY i_device, i_time
) t
) t1 LEFT JOIN (
SELECT i_device, min(rn) min_rn, max(rn) max_rn FROM (
SELECT *, rowNumberInAllBlocks() rn FROM (
SELECT i_device, i_time
FROM tbl
ORDER BY i_device, i_time
) t
) t GROUP BY i_device
) t2 USING (i_device)

How to select a max row for each group in SQL

I want select countries with maximum value of 'Value' for a 'grpid'. Also already selected 'Country' should not be considered for other 'grpid' while checking the maximum. ( ie Country or grpid should not be repeated in the result )
SQL Fiddle
Result:
Country grpid Value Row_number
US 49707 604456458 1
GB 5086 497654945 4
CA 909 353500201 10
JP 231 198291290 15
try this query instead,
WITH OrderedOrders AS
(
SELECT country,grpid,value,ROW_NUMBER() OVER(PARTITION BY country ORDER BY country,value DESC) AS 'RowNumber'
FROM test1
)
select * from OrderedOrders
where RowNumber =1
I believe this is what you're looking for:
SQL Fiddle
;with cte as
(
select
country,
max(value) as MaxVal,
min(row_number) as MinRow
from test1
group by Country
)
select
c.country,
t.grpid,
c.MaxVal,
c.MinRow
from cte c
join test1 t
on t.country = c.country
and t.value = c.MaxVal
and t.row_number = c.MinRow
order by country, grpid
Can you please try out this query
select
country,
value,
grpid,
count(*)
from test1
group by
country,
value,
grpid
order by
country,
value desc

How to reverse the table that comes from SQL query which already includes ORDER BY

Here is my query:
SELECT TOP 8 id, rssi1, date
FROM history
WHERE (siteName = 'CCL03412')
ORDER BY id DESC
This the result:
How can I reverse this table based on date (Column2) by using SQL?
You can use the first query to get the matching ids, and use them as part of an IN clause:
SELECT id, rssi1, date
FROM history
WHERE id IN
(
SELECT TOP 8 id
FROM history
WHERE (siteName = 'CCL03412')
ORDER BY id DESC
)
ORDER BY date ASC
You could simply use a sub-query. If you apply a TOP clause the nested ORDER BY is allowed:
SELECT X.* FROM(
SELECT TOP 8 id, Column1, Column2
FROM dbo.History
WHERE (siteName = 'CCL03412')
ORDER BY id DESC) X
ORDER BY Column2
Demo
The SELECT query of a subquery is always enclosed in parentheses. It
cannot include a COMPUTE or FOR BROWSE clause, and may only include an
ORDER BY clause when a TOP clause is also specified.
Subquery Fundamentals
try the below :
select * from (SELECT TOP 8 id, rssi1, date
FROM history
WHERE (siteName = 'CCL03412')
ORDER BY id DESC ) aa order by aa.date DESC
didn't run it, but i think it should go well
WITH cte AS
(
SELECT id, rssi1, date, RANK() OVER (ORDER BY ID DESC) AS Rank
FROM history
WHERE (siteName = 'CCL03412')
)
SELECT id, rssi1, date
FROM cte
WHERE Rank <= 8
ORDER BY Date DESC
I have not run this but i think it will work. Execute and let me know if you face error
select id, rssi1, date from (SELECT TOP 8 id, rssi1, date
FROM history
WHERE (siteName = 'CCL03412')
ORDER BY id DESC) order by date ;

ORA-00907: missing right parenthesis

I'm getting the error " ORA-00907: missing right parenthesis"
but I've checked and all the parenthesis are there, so I'm stumped.
My query is
SELECT
SUM(score) as score,
facebook_id,
firstname,
lastname,
dense_rank(score)
WITHIN GROUP ( ORDER BY score ) as rank_db
FROM
(
SELECT DISTINCT *
FROM
(
SELECT *
FROM fanta_score
ORDER BY score desc
) as f
GROUP BY
facebook_id, game_id
) as g
GROUP BY facebook_id
ORDER BY score DESC, created_at
LIMIT 50
I'm by no means an Oracle expert, but I have to use it due the hosting environment its has to be in.
LIMIT command isn't recognized in Oracle. And should use ROWNUM instead of Limit.
SELECT
SUM(score) as score,
facebook_id,
firstname,
lastname,
dense_rank(score)
WITHIN GROUP ( ORDER BY score ) as rank_db
FROM
(
SELECT DISTINCT *
FROM
(
SELECT *
FROM fanta_score
ORDER BY score desc
) as f
GROUP BY
facebook_id, game_id
) as g
WHERE ROWNUM = 50
GROUP BY facebook_id
ORDER BY score DESC, created_at

SQL Query, SELECT Top 2 by Foreign Key Order By Date

I need a SQL query that returns the top 2 Plans by PlanDate per ClientID. This is all on one table where PlanID is the PrimaryID, ClientID is a foreignID.
This is what I have so far -->
SELECT *
FROM [dbo].[tblPlan]
WHERE [PlanID] IN (SELECT TOP (2) PlanID FROM [dbo].[tblPlan] ORDER BY [PlanDate] DESC)
This, obviously, only returns 2 records where I actually need up to 2 records per ClientID.
This can be done using ROW_NUMBER:
SELECT PlanId, ClientId, PlanDate FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY ClientId ORDER BY PlanDate DESC) rn, *
FROM [dbo].[tblPlan]
) AS T1
WHERE rn <=2
Add any other columns you need to the select to get those too.
Edit, Dec 2011. Corrected CROSS APPLY solution
Try both to see what is best
SELECT *
FROM
( -- distinct ClientID values
SELECT DISTINCT ClientID
FROM [dbo].[tblPlan]
) P1
CROSS APPLY
( -- top 2 per ClientID
SELECT TOP (2) P2.PlanID
FROM [dbo].[tblPlan] P2
WHERE P1.ClientID = P2.ClientID
ORDER BY P2.[PlanDate] DESC
) foo
Or
;WITH cTE AS (
SELECT
*,
ROW_NUMBER () OVER (PARTITION BY clientid ORDER BY [PlanDate] DESC) AS Ranking
FROM
[dbo].[tblPlan]
)
SELECT * FROM cTE WHERE Ranking <= 2