找出日期的差距

时间:2015-06-11 08:09:42

标签: sql sql-server sql-server-2008 tsql stored-procedures

我有一个包含3列的表格:

 <script>
        var url = "Band";
      $(document).ready(function () {
          //   Send an AJAX request

            $.getJSON(url)
           .done(function (data) {



      //   On success, 'data' contains a list of products.
           $.each(data, function (key, item) {
              //      Add a list item for the product.
         $('<li>', { text: formatItem(item) }).appendTo($('#begin'));



      });
          });
     });     



function formatItem(item) {
            return "ID: " + item.id + ":" + item.name + ': $' + item.price + "Category: " + item.category;
        }

此表中有很多数据。并非所有日历日期都显示在表格中。如何找到日期差距大于Date smalldatetime not null Val1 decimal not null Val2 decimal not null 天的所有地方?

2 个答案:

答案 0 :(得分:2)

以下是如何执行此操作的方法:

DECLARE @t TABLE
    (
      Date SMALLDATETIME NOT NULL ,
      Val1 DECIMAL NOT NULL ,
      Val2 DECIMAL NOT NULL
    )

INSERT INTO @t VALUES
('20150101', 1, 1),
('20150104', 1, 1),
('20150109', 1, 1),
('20150201', 1, 1),
('20150305', 1, 1),
('20150506', 1, 1)


;WITH cte AS(SELECT *, ROW_NUMBER() OVER(ORDER BY Date) AS Rn FROM @t)
SELECT c2.*, c1.Date AS PrevDate FROM cte c1
JOIN cte c2 ON c1.Rn = c2.Rn - 1
WHERE DATEDIFF(d, c1.Date, c2.Date) > 30 --this is your X

输出:

Date                Val1    Val2    Rn  PrevDate
2015-03-05 00:00:00 1       1       5   2015-02-01 00:00:00
2015-05-06 00:00:00 1       1       6   2015-03-05 00:00:00

答案 1 :(得分:0)

您可以在SQL Server数据库中创建日期表并使用SQL date table to find gaps in date

日期表是包含所有可能日期的参考表。您将比较目标表和日期列加入日期列并列出缺失的列表