我有下面的SQL代码,
SELECT s.[CusNo] Supp,
RTRIM(CAST(s.[Customer] AS VARCHAR(50))) AS Name,
s.[ConNo] Con,
RTRIM(CAST(s.[ConN] AS VARCHAR(50))) AS ConN,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELL else 0 end) ActualSales
FROM [dbo].[Reports] s
WHERE s.BOX = 2
AND s.SELL <> 0
GROUP BY s.[CusNo], s.[Customer], s.ConNo, s.ConN
执行上述查询时,我在ActualSales列中获取了所有值(包括0个值)。
如何删除值为0的行?
答案 0 :(得分:2)
使用having
子句
SELECT s.[CusNo] Supp,
RTRIM(CAST(s.[Customer] AS VARCHAR(50)) ) AS Name,
s.[ConNo] Con,
RTRIM(CAST(s.[ConN] AS VARCHAR(50)) ) AS ConN,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELL else 0 end) ActualSales
FROM [dbo].[Reports] s
WHERE s.BOX = 2 and s.SELL <> 0
GROUP BY s.[CusNo], s.[Customer], s.ConNo, s.ConN
having sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELL else 0 end)<>0
或者您可以使用子查询
select * from
(
SELECT s.[CusNo] Supp,
RTRIM(CAST(s.[Customer] AS VARCHAR(50)) ) AS Name,
s.[ConNo] Con,
RTRIM(CAST(s.[ConN] AS VARCHAR(50)) ) AS ConN,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELL else 0 end) ActualSales
FROM [dbo].[Reports] s
WHERE s.BOX = 2 and s.SELL <> 0
GROUP BY s.[CusNo], s.[Customer], s.ConNo, s.ConN
)A where ActualSales<>0
答案 1 :(得分:0)
我认为您可以通过将case
条件移到where
子句来获得所需的内容:
SELECT s.[CusNo] as Supp,
RTRIM(CAST(s.[Customer] AS VARCHAR(50)) ) AS Name,
s.[ConNo] as Con,
RTRIM(CAST(s.[ConN] AS VARCHAR(50)) ) AS ConN,
SUM(s.SELL) as ActualSales
FROM [dbo].[Reports] s
WHERE s.BOX = 2 AND s.SELL <> 0 AND
s.Date BETWEEN convert(date, dateadd(wk, datediff(week, 0, getdate()) - 1, 0) - 1) and
convert(date,dateadd(wk, datediff(week, 0, getdate()) - 1, 0) + 5)
GROUP BY s.[CusNo], s.[Customer], s.ConNo, s.ConN;
ActualSales
可能仍然是0
(如果Sales
可能为负。在这种情况下,您需要一个HAVING
子句:{{1} }。
由于此方法会在聚合之前进行过滤,因此也可能会提高性能。