试图在查询中获得单行?

时间:2013-10-25 15:29:18

标签: tsql

我试图在case语句中获取单个记录,我想在哪里将seelect语句放在top(1)

 CASE WHEN CAST(VehicleCC AS MONEY) BETWEEN -1 AND 50 THEN '33.94'
                          WHEN CAST(VehicleCC AS MONEY) BETWEEN 51 AND 125 THEN '39.65' 
                          WHEN CAST(VehicleCC AS  MONEY) BETWEEN 126 AND 500 THEN '55.90' 
                          WHEN CAST(VehicleCC AS  MONEY) BETWEEN 501 AND 650 THEN '67.31'
                          WHEN CAST(VehicleCC AS MONEY) BETWEEN 651 AND 1000 THEN '78.65' 
                          WHEN CAST(VehicleCC AS MONEY ) > 1001 THEN '79.85' 
                          else 
                           (SELECT TOP(1) cast (VehicleCC as varchar (50)) FROM  HIRE_INSTRUCTION HIRP 
                              INNER JOIN VEHICLE VEH ON HIRP.FKFleetVehicleID=VEH.vehicleid
                              WHERE HIRP.FKBLDRefID=cl.FKBLDRefID AND HIRP.Deleted=0 AND VEH.Deleted=0
                                ORDER BY veh.VehicleCC DESC) END AS [Hire Rate Charged Per Day],

2 个答案:

答案 0 :(得分:0)

如果TOP(1)不起作用,请尝试RANK():

SELECT VehicleCC
FROM (
    SELECT CAST(VEH.VehicleCC as varchar (50)),
        RANK() OVER(ORDER BY CAST(VEH.VehicleCC as varchar (50))) AS CCRank
    FROM  HIRE_INSTRUCTION HIRP 
        INNER JOIN VEHICLE VEH 
            ON HIRP.FKFleetVehicleID=VEH.vehicleid
    WHERE HIRP.FKBLDRefID=cl.FKBLDRefID 
        AND HIRP.Deleted=0 
        AND VEH.Deleted=0
    ORDER BY veh.VehicleCC DESC
    ) CC
WHERE CCRank = 1

答案 1 :(得分:0)

您可以使用set rowcount来限制查询返回的行数。

set rowcount 1 -- the query will return one record

select * from table 

set rowcount 0 --back to normal