报告中存在的项目天数

时间:2013-02-28 22:52:50

标签: sql sql-server-2008 tsql

我有一张表存储特定报告的每日运行。

DateAdded NodeId Field1Value Field1Threshold etc

我现在有一个新要求,列出NodeId在报告中出现的天数。因此,如果DateAdded列为

2013-03-01   <-- Run date
2013-02-28
2013-02-27
2013-02-26   <-- End of date sequence.  Return 4 days
2013-02-13
2013-01-07

这也是关于识别日期序列中的中断

编辑10:54 am我的时间 这是我的sp中带有第一个建议的where子句

        t.etc,
        t.blah,
        CASE WHEN ras1.NodeId IS NULL THEN 'N' ELSE 'Y' END as AlertStat,
        fl.NodeId as fl_NodeId, 
        DATEDIFF(day, fl.LastDate, fl.FirstDate) as [DaysOn]
FROM    vwTrips t left join
        (
            select distinct nodeId 
            from    CustLogs.dbo.ReportAlertStats ras 
            where   ras.DateAdded between @RasStart and @RasEnd
        ) ras1 on  t.NodeId = ras1.NodeId left join
        (   SELECT NodeId, 
                    MIN(DateAdded) [FirstDate], 
                    MAX(DateAdded) [LastDate]
            FROM CustLogs.dbo.ReportAlertStats
            GROUP BY NodeId
            --ORDER BY NodeId, DateAdded
        ) fl on t.NodeId = fl.NodeId
WHERE   t.TripStart between @ReportStart and @ReportEnd

2 个答案:

答案 0 :(得分:0)

SELECT fl.NodeId, DATEDIFF(day, fl.FirstDate, fl.LastDate) [Days On] FROM
(SELECT NodeId, MIN(DateAdded) [FirstDate], MAX(DateAdded) [LastDate]
FROM DailyRuns
GROUP BY NodeId
) fl

对于仅出现一次的NodeId,它将显示与第一次和最后一次出现在同一天相同的结果。

SQL小提琴:http://sqlfiddle.com/#!3/ea373/7

答案 1 :(得分:0)

这会回答你的问题吗?

select nodeid, count(distinct dateAdded) as NumDays
from DailyRuns dr
group by nodeid