如何使用sql server动态获取数据?

时间:2017-08-24 09:51:50

标签: sql-server

我从table.now最后7天为get数据创建了一个查询。现在我想让这个查询动态地改变几天使用点击按钮。然后我在查询中更改了一些然后可能日期变化很好但我的数据来自当前日期数据。所以我在这里犯了小错,但我不知道。

这是我的查询=>

SELECT CAST(dateadd(day, T.i, CAST(DATEADD(day,0, GETDATE()) AS Date) AS DateColumn, uf.TotalCount
    FROM (VALUES (-6), (-5), (-4), (-3), (-2), (-1), (0)) AS T(i)
    OUTER APPLY
    (
       SELECT COUNT(UF.InsertDateTime) AS TotalCount
       FROM Users UF               
       WHERE DATEDIFF(DAY,UF.InsertDateTime, DATEADD(DAY, T.i, GETDATE())) = 0 and UF.IsLogin = 1
    ) uf

这是我在表格中的数据=>

UserId | IsLogin | InsertDateTime
-------+---------+---------------------------
 1         1        2017-08-24 16:12:46.713
 2         1        2017-08-23 16:50:55.789
 3         1        2017-08-22 16:12:46.713
 4         1        2017-08-21 16:12:46.713
 5         1        2017-08-20 16:12:46.713
 6         1        2017-08-19 16:12:46.713
 7         1        2017-08-18 16:12:46.713  

我当前的o / p =>

DateColumn  |  TotalCount
2017-08-18       1
2017-08-19       1
2017-08-20       1
2017-08-21       1
2017-08-22       1
2017-08-23       1
2017-08-24       1

这是我的o / p是正确的。但在我的查询中我有更改日 0 以替换 -6 然后我想要更改前7天。前7天到了,但在数据库中数据不是availbale但结果总是得到1 1 1之类的..

这是我的查询更改days =>

 SELECT CAST(dateadd(day, T.i, CAST(DATEADD(day,-6, GETDATE()) AS Date) AS DateColumn, uf.TotalCount
    FROM (VALUES (-6), (-5), (-4), (-3), (-2), (-1), (0)) AS T(i)
    OUTER APPLY
    (
       SELECT COUNT(UF.InsertDateTime) AS TotalCount
       FROM Users UF               
       WHERE DATEDIFF(DAY,UF.InsertDateTime, DATEADD(DAY, T.i, GETDATE())) = 0 and UF.IsLogin = 1
    ) uf

在查询-6中的更改日之后,然后获得此结果=>

 DateColumn  |  TotalCount
2017-08-12       1
2017-08-13       1
2017-08-14       1
2017-08-15       1
2017-08-16       1
2017-08-17       1
2017-08-18       1

但是表格数据中的日期12到17不可用。所以我想纠正日期数据。

1 个答案:

答案 0 :(得分:2)

试试这个

 SELECT dateadd(day, T.i, CAST(DATEADD(day,-6, GETDATE()) AS Date)), uf.TotalCount
    FROM (VALUES (-6), (-5), (-4), (-3), (-2), (-1), (0)) AS T(i)
    OUTER APPLY
    (
       SELECT COUNT(UF.InsertDateTime) AS TotalCount
       FROM user1 UF               
       WHERE DATEDIFF(DAY,UF.InsertDateTime, dateadd(day, T.i, CAST(DATEADD(day,-6, GETDATE()) AS Date))) = 0 and UF.IsLogin = 1
    ) uf