0

I need the following query to return a message, such as "No Result" if the Record Count = 0.

set @ID_CARTERA = 1;

select    

LEFT(A.F_ANOTRIMESTRE, 4 ) Year,
RIGHT(A.F_ANOTRIMESTRE, 2 ) Quarter,
ROUND ( A.POR_RENTABILIDAD, 2 ) Quarterly_Yield

from      dr_rent_carteras_trimestres A

where     A.ID_CARTERA = @ID_CARTERA
And       (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select    MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
                                         from      dr_rent_carteras_trimestres
                                         where     ID_CARTERA = @ID_CARTERA ) 
            and
            RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12) 
4

1 回答 1

0

你可以像这样欺骗系统:

  1. 生成查询以返回 COUNT(*)。这将始终返回一行,即使要计算的行数为零

  2. 使用 COUNT(*) 查询左连接您的主查询。使用 Case 语句将结果替换为“无结果”。

因此,结果查询将如下所示(假设 - 主查询仅返回零或一条记录 - 因此 LEFT JOIN 中没有 ON 子句!!!!!!):

set @ID_CARTERA = 1;

select    
CASE cnt WHEN 0 THEN "No Results" ELSE Year END,
Quarter,
Quarterly_Yield
FROM
(select count(*) AS cnt
from      dr_rent_carteras_trimestres A
where     A.ID_CARTERA = @ID_CARTERA
And       (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select    MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
                                         from      dr_rent_carteras_trimestres
                                         where     ID_CARTERA = @ID_CARTERA ) 
            and
            RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12) ) cnt_tbl
LEFT JOIN
( select    
LEFT(A.F_ANOTRIMESTRE, 4 ) Year,
RIGHT(A.F_ANOTRIMESTRE, 2 ) Quarter,
ROUND ( A.POR_RENTABILIDAD, 2 ) Quarterly_Yield
from      dr_rent_carteras_trimestres A
where     A.ID_CARTERA = @ID_CARTERA
And       (LEFT(A.F_ANOTRIMESTRE, 4 ) = ( select    MAX(left(F_ANOTRIMESTRE, 4 ) ) - 0
                                         from      dr_rent_carteras_trimestres
                                         where     ID_CARTERA = @ID_CARTERA ) 
            and
            RIGHT(A.F_ANOTRIMESTRE, 2 ) = 12) ) main_tbl

使用 UNION 也可以完成同样的事情。如果您希望我展示如何在评论中询问

于 2013-02-01T03:13:32.387 回答