SQL - 显示零结果

时间:2010-07-07 22:25:15

标签: sql sql-server-2005

我希望在根据我的查询找不到记录时显示“O”或“找不到结果”,但无法正确显示。我认为问题来自于我试图显示有关我正在计算的记录的信息以及有多少符合标准的记录。也许它不是我需要用ISNULL改变的计数,而是在没有输出行的情况下修改结果的东西。

提前感谢您的帮助。

select t3.countyname, t2.titleunitname, t1.transdesc, count (isnull(t3.orderkey,0)) as c1
        from tblorder as t3
        left join qryOrderRecord1 as t1 on t3.OrderKey = t1.OrderKey
        left join qrytitleunits as t2 on t3.titleunitnum = t2.titleunitnum
        WHERE t1.transdesc = 'LETTERS'
        AND (t3.OrderDateTime between '7/7/2010' AND '7/7/2010')
        AND t3.countyname = 'Frankfurt'
        AND t2.titleunitname = 'Maxwell'
        group by t3.countyname,t1.transdesc, t2.titleunitname

3 个答案:

答案 0 :(得分:2)

我认为您需要计算t1.orderkey t3位于外部联接的左侧,因此t1.orderkey值为NULL

我还将t1和t2上的过滤器移动到JOIN条件而不是WHERE子句

如果不这样做,在你的问题中提供一些样本数据会有所帮助。

SELECT t3.countyname,
    t2.titleunitname,
    t1.transdesc    ,
    COUNT(t1.orderkey) AS c1 /*As dotjoe's answer suggests*/
FROM tblorder                     AS t3
    LEFT JOIN qryOrderRecord1     AS t1
    ON  t3.OrderKey  = t1.OrderKey
    AND t1.transdesc = 'LETTERS'
    LEFT JOIN qrytitleunits AS t2
    ON  t3.titleunitnum  = t2.titleunitnum
    AND t2.titleunitname = 'Maxwell'
WHERE t3.OrderDateTime BETWEEN '7/7/2010' AND '7/7/2010' /*Seems odd! Should these be 
                                                           different dates?*/
AND t3.countyname = 'Frankfurt'
GROUP BY t3.countyname,
    t1.transdesc      ,
    t2.titleunitname

答案 1 :(得分:2)

count(isnull(column, 0))count(1)count(*)相同。看到这个问题的原因......

Count(*) vs Count(1)

也许你想要count(t1.orderkey)?这不会计算任何null t1.orderkey的。

答案 2 :(得分:0)

给这一点。

select t3.countyname, t2.titleunitname, t1.transdesc, count (isnull(t3.orderkey,0)) as c1 
into #Tmp
from tblorder as t3 
    left join qryOrderRecord1 as t1 on t3.OrderKey = t1.OrderKey 
    left join qrytitleunits as t2 on t3.titleunitnum = t2.titleunitnum 
where t1.transdesc = 'LETTERS' 
  AND (t3.OrderDateTime between '7/7/2010' AND '7/7/2010') 
  AND t3.countyname = 'Frankfurt' 
  AND t2.titleunitname = 'Maxwell' 
group by t3.countyname,t1.transdesc, t2.titleunitname 

if @@ROWCOUNT > 0
    select *
    from #Tmp
else
    select 'No Results Found.'