如果没有找到行,则返回单行

时间:2011-08-31 05:13:05

标签: sql sql-server

我们用于CrystalReport的这个T-SQL查询。

SELECT COUNT(*) AS Expr1, [Date], StoreNumber
FROM   dbo.Orderp
WHERE  (OpServerNumber = 0)
GROUP BY [Date], StoreNumber

如果没有行对特定日期和商店有效,则会出现问题。

如果查询找不到表中的任何行,是否可以返回Expr1 = 0的单行?

6 个答案:

答案 0 :(得分:4)

如果您想要至少一行,则可以使用EXISTS条件:

IF EXISTS(SELECT COUNT(*) AS Expr1, [Date], StoreNumber FROM   dbo.Orderp WHERE  (OpServerNumber = 0) GROUP BY [Date], StoreNumber)
    SELECT COUNT(*) AS Expr1, [Date], StoreNumber FROM   dbo.Orderp WHERE  (OpServerNumber = 0) GROUP BY [Date], StoreNumber
ELSE
    SELECT 0 AS Expr1, NULL [Date], 0 StoreNumber 

答案 1 :(得分:0)

如果您将此封装在存储过程中,则可以:

  • 将这些行选择为表变量或临时表
  • 检查@@ROWCOUNT,如果是IF @@ROWCOUNT = 0,则明确向该临时表添加虚拟行
  • 作为存储过程
  • 的结果,从SELECT * FROM .....中的临时表中返回内容

答案 2 :(得分:0)

问题是你在单一选择中使用count(*)和其他列。

如果

查询满足where子句,它将至少获得一行。

您需要将count(*)和仅列查询分开。

答案 3 :(得分:0)

SELECT 
    COUNT(*) AS Expr1, [Date], StoreNumber 
FROM dbo.Orderp WHERE  (OpServerNumber = 0) GROUP BY [Date], StoreNumber

if @@ROWCOUNT = 0
    SELECT 0 AS Expr1, NULL [Date], 0 StoreNumber 

答案 4 :(得分:0)

select Expr1, [Date], StoreNumber from (
    select *,row_number() over (order by isrealrow desc) rownum from (
        select COUNT(*) as Expr1,[Date], StoreNumber, 1 as isrealRow FROM  dbo.Orderp
        WHERE  (OpServerNumber = 0)
        GROUP BY [Date], StoreNumber
        union
        select 0, NULL, NULL, 0 as isrealrow 
    ) b
)c
where isrealRow=1 or rownum=1

这是我整天写的最酷的SQL。

答案 5 :(得分:0)

SELECT ISNULL(B.num,0) AS Expr1, A.[Date], A.StoreNumber
FROM 
(SELECT [Date], StoreNumber FROM dbo.Orderp GROUP BY [Date], StoreNumber) A
LEFT OUTER JOIN
(SELECT COUNT(*) AS num, [Date], StoreNumber
FROM   dbo.Orderp
WHERE  (OpServerNumber = 0)
GROUP BY 
[Date], StoreNumber) B ON A.[Date]=B.[Date] AND A.StoreNumber=B.StoreNumber

编辑:我只是想到了另一个......

SELECT
SUM(Expr1) AS Expr1, [Date], StoreNumber
FROM
(SELECT 0 AS Expr1, [Date], StoreNumber, NULL AS OpServerNumber
FROM   dbo.Orderp
GROUP BY [Date], StoreNumber
UNION ALL
SELECT 1, [Date], StoreNumber, OpServerNumber
FROM   dbo.Orderp)T
WHERE OpServerNumber IS NULL OR OpServerNumber = 0
GROUP BY [Date], StoreNumber