• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 247
  • Last Modified:

SQL Query with more that one "SELECT TOP 1"

Greetings,
I am trying to generate a SQL query where I can select more than one "TOP 1".

For instance, I might want the top 1 from one column and the top 1 from another column, both being in different rows.

SELECT TOP 1 'Column1' as x, TOP 1 'Column3' as y, Z FROM TableA WHERE Z LIKE '%str%'

Please let me know if this requires more explanation.  Thanks in advance!
0
MaxKroy
Asked:
MaxKroy
  • 3
1 Solution
 
degarayCommented:
You can use two subqueries for that, see the code:

I hope it helps you

Cheers!
SELECT(
   SELECT TOP 1 'Column1' 
   FROM TableA WHERE Z LIKE '%str%)
   AS x, (
   SELECT TOP 1 'Column3'
   FROM TableA WHERE Z LIKE '%str%
   ) AS y

Open in new window

0
 
degarayCommented:
Depending on the data on your tables you might need to add a LIMIT 1, 0

So this should be the code then.
SELECT(
   SELECT TOP 1 'Column1' 
   FROM TableA WHERE Z LIKE '%str% LIMIT 1,0
   ) AS x, (
   SELECT TOP 1 'Column3'
   FROM TableA WHERE Z LIKE '%str% LIMIT 1,0
   ) AS y

Open in new window

0
 
degarayCommented:
Sorry like this:
SELECT(
   SELECT TOP 1 'Column1' 
   FROM TableA WHERE Z LIKE '%str% LIMIT 0, 1
   ) AS x, (
   SELECT TOP 1 'Column3'
   FROM TableA WHERE Z LIKE '%str% LIMIT 0, 1
   ) AS y

Open in new window

0
 
MaxKroyAuthor Commented:
Thank you Obi-one. You are my only hope.
0

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now