在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次搜索,这将花费更少的时间....对吗?
答案 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