2015-11-04 137 views
1

我想写一个查询,执行以下操作:计数天凡记录未记录SQL

  • 组的结果由'key'
  • 和的次数的'device id'没有记录'data'

这是样本数据

sample data

最终的输出应该是这样的:

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

哪里count of missed data是一个'device id'没有在最近365天记录'data'天数。

**注意:每'key'可能有500 'device id'。每次在这一年的某个日历日,这些设备中的一个设备不会记录'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 

回答

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 
+0

我想我可能有在我的问题上有点不清楚。每个密钥将有多个“设备ID”。每个键可以有500个“设备ID”。我需要统计每个设备在整个一年中每天没有记录“数据”的次数。这是否有意义? – johnwonderbread

+0

@johnwonderbread查看我的编辑 – RedFilter

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; 
+0

我想我的问题可能有点不清楚。每个密钥将有多个“设备ID”。每个键可以有500个“设备ID”。我需要统计每个设备在整个一年中每天没有记录“数据”的次数。 这有意义吗? – johnwonderbread

+0

@johnwonderbread。 。 。我非常肯定,这就是这个查询所做的事情(虽然我毫不犹豫地承认它可能会有一个错误)。 –

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] 
+0

谢谢。问题 - 如果某些日期有多个数据条目(例如:上午10点和下午11点),这是否会影响此查询的结果?我只想让它在没有阅读的每一天都计算一次,而不考虑一天的时间。 – johnwonderbread

+0

不,一天内的多个日期条目会以“count(distinct cast(mt。[Date] as date))”每天被折叠为1“)” – JBrooks