列出所有记录并计算它们在SQL中的日期范围中使用的次数

时间:2016-05-16 16:08:38

标签: mysql sql-server sql-server-2014

我在表格中列出了158个独特的项目。我试图将这些物品在特定日期范围内运送给客户的次数。我需要在运行查询时列出所有158个项目。如果它没有在那个时间段内发货我想要一个0来计算。到目前为止,如果不在该日期范围内,我不会列出该项目。我确信这很令人厌恶,我只是在想它。

 select Applicator
, count(fshipdate) as 'Times Used'
,sum(fqty_iss) as 'Terminal count'
from HowOftenUsed
where Applicator <> ''
and fshipdate between '01/01/2016' and '05/16/2016'
group by Applicator

2 个答案:

答案 0 :(得分:1)

这适用于所有数据库引擎

select Applicator,
       count(case when fshipdate not between '01/01/2016' and '05/16/2016' 
                  then null 
                  else fshipdate 
             end) as 'Times Used',
       sum(case when fshipdate not between '01/01/2016' and '05/16/2016' 
                then null 
                else fqty_iss 
           end) as 'Terminal count'
from HowOftenUsed
where Applicator <> ''
group by Applicator

答案 1 :(得分:0)

首先找到表格中的158个唯一项目,并使用Left Outer Join列表制作distinct

;WITH cte 
     AS (SELECT DISTINCT applicator 
         FROM   howoftenused) 
SELECT C.applicator, 
       Count(fshipdate) AS 'Times Used', 
       Sum(fqty_iss)    AS 'Terminal count' 
FROM   cte C 
       LEFT OUTER JOIN howoftenused H 
                    ON C.applicator = H.applicator 
                       AND fshipdate BETWEEN '01/01/2016' AND '05/16/2016' 
WHERE  C.applicator <> '' 
GROUP  BY C.applicator