SQL从另一个选择查询中进行多重选择

时间:2019-06-13 09:18:17

标签: sql sql-server

在Microsoft SQL Server中,有没有办法从单个Select中进行选择?

类似的东西:

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

我知道我可以做到:

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

但是我认为这将花费更多时间,因为它将在大数据库中执行许多不必要的搜索

但是第一个代码将只在大型数据库中进行1次搜索,而在小型数据库中进行X次搜索,这将花费更少的时间....对吗?

1 个答案:

答案 0 :(得分:2)

您可以使用CASE WHEN语句。

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