计算记录未记录SQL的天数

时间:2015-11-04 01:55:50

标签: sql-server count

我正在尝试编写执行以下操作的查询:

  • 'key'
  • 对结果进行分组
  • 汇总'device id'未记录'data'
  • 的次数

这是样本数据

sample data

最终输出应如下所示:

|  Key  |  Count of Missed Data  |
|  14   |          123           |
|  124  |          356           |

其中count of missed data是“device id'在过去365天内未记录'data'的天数。

**注意:每'device id'可能有500 'key'。每当其中一台设备在一年中的某个日历日没有记录'data'时,我需要计算一下,并按键分组“错过的数据”总数。

如果您有任何疑问,请询问。谢谢你的帮助!

约翰

根据以下建议,这是我正在运行的代码。批评?

Select 
a.descr AS 'Community',
a.meter_type AS 'Meter Type',
sum(a.misseddaysperdevice) as [Count of Missed Days]
From
    (
    Select 
        fmr.subdivisionkey, 
        sub.descr,
        meter_type,
        365-count(distinct(convert(varchar, fmr.read_date, 112))) as misseddaysperdevice
    From 
        FactMeterRead fmr
        INNER JOIN DimSubdivision sub on sub.subdivisionkey = fmr.subdivisionkey
    Where 
        fmr.read_date > getdate()-364
    Group By 
        fmr.SubdivisionKey, sub.descr, fmr.meter_num, meter_type
    ) a 
Group By 
    a.descr, meter_type
Order By 
    [Count of Missed Days] DESC

3 个答案:

答案 0 :(得分:1)

这样的事情应该这样做:

select key, 365 - count(distinct(cast(date as date))) as [Count of Missed Data]
from MyTable
where date > getdate() - 365
group by key

编辑:要计算给定密钥的所有设备的错过天数,请尝试以下操作:

select key, sum(MissedDaysPerDevice) as [Count of Missed Data]
from (
    select key, 365 - count(distinct(cast(date as date))) as MissedDaysPerDevice
    from MyTable
    where date > getdate() - 365
    group by key, device
) a
group by key

答案 1 :(得分:1)

嗯,错过的天数是365天。这更容易计算,所以:

select key, count(distinct cast(date as date)) as days_present,
       365 - count(distinct cast(date as date)) as days_absent
from t
where date >= dateadd(day, -364, cast(getdate() as date))
group by key;

答案 2 :(得分:1)

我不喜欢硬编码365天....问题1/4的时间......

         declare @asOfDate date = getdate()
         declare @start date
         set @start = dateadd(year, -1,  @asOfDate)

         select sumDevice.[Key], sum(sumDevice.MissingDaysCount) as MissingDaysCount
         from ( 
            select mt.[Key], 
            mt.[device id],
            datediff(day, @start, @asOfDate) - isnull(count(distinct cast(mt.[Date] as date)), 0) 
                                             as [MissingDaysCount]
            from myTable mt
            where mt.[date] between @start and dateadd(day, 1, @asOfDate)
            group by mt.[key],
                     mt.[device id]) as SummaryKey
         group by sumDevice.[Key]   
         order by sumDevice.[Key]