1

Is there any way to do selects from a single Select in Microsoft SQL Server?

Something like :

SELECT id, type, name, address  
FROM Persons AS Persons_DATA 
WHERE (name='...' OR name in ('...','...'))

SELECT TOP 1 'Best Vendor : '+name from Persons_DATA where type=1 order by ...
union SELECT TOP 1 'Best Customer : '+name from Persons_DATA where type=2 order by ...
union SELECT TOP 1 'Least Debt : '+name from Persons_DATA where ... order by ...
union SELECT TOP 1 'Most Debt : '+name from Persons_DATA where ... order by ...
...

I know I can do :

SELECT TOP 1 
    'Best Vendor : '+name 
FROM
    Persons 
WHERE
    type = 1 AND (name='...' OR name in ('...','...')) 
ORDER BY ...

UNION

SELECT TOP 1 
    'Best Customer : '+name 
FROM
    Persons 
WHERE
    type = 2 
    AND (name='...' OR name in ('...','...')) 
ORDER BY ...

But I think this will take more time because it will do many unnecessary searches in a big data base

but the first code will only do 1 search in the big database and X searches in a small database and it will take less time.... am I right?

3
  • 2
    TOP without an ORDER BY? I don't understand what are you trying to do there. Commented Jun 13, 2019 at 9:24
  • Actually its just some test code the actual question is I want to do some sub-selects from a select Commented Jun 13, 2019 at 9:25
  • anyway , I added a ORDER BY to avoid misunderstanding Commented Jun 13, 2019 at 9:27

1 Answer 1

2

You can use CASE WHEN statement..

SELECT CASE WHEN type=1 THEN 'Best Vendor : '+name 
   WHEN type=2 THEN 'Best Customer: '+name 
    WHEN type=3 THEN 'Least Debt: '+name 
     WHEN type=4 THEN 'Most Debt: '+name ELSE '....'  END  
from Persons  A 
LEFT JOIN (SELECT RANK() OVER (PARTITION BY type ORDER BY id DESC) Rk, name from Persons    
        WITH(NOLOCK) ) AS PS  ON PS.Id = A.id   and Rk=1   
Sign up to request clarification or add additional context in comments.

6 Comments

Oh thanks i think this will solve my problem but I guess you did a small mistake in CASE WHEN Syntax : w3schools.com/sql/sql_case.asp
Is there anyway to contain a count() or sum() in this querry? and I also dont understand this LEFT JOIN (SELECT RANK() OVER (PARTITION BY type ORDER BY id DESC) Rk, name from Persons WITH(NOLOCK) ) AS PS ON PS.Id = A.id and Rk=1
which count you want? type wise OR total sum?
select count of total rows with type 2 something like : Least debt : Customer , Total customers with debt : 100
Left join takes the latest record, instead of top 1 in each types
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.