Sql日期范围与金额

时间:2014-09-01 07:01:59

标签: sql

我想以帐户语句格式排列数据,但我完全不知道编写SQL命令,尤其是日期范围。

表A

Creditors name       Invoice No         Due date          Outstanding Amt
Company A            A001              1/8/2014            1500
Company B            A002              1/6/2014             300
Company B            A003              1/7/2014             900
Company B            A004              5/7/2014              50        
Company c            A005              31/12/2014           200

结果,发言日期:2014年11月8日

Creditors name    0-30 Days    31-60 Days   61-90 Days   Over 90 Days   Amt Due        
Company A          1500           0           0              0           1500
Company B             0           950          300            0           1250
Company c             0            0           0             200           200

请帮助&谢谢

3 个答案:

答案 0 :(得分:0)

您可以使用下面提到的查询获取记录。

SELECT *
FROM periods
WHERE range_start <= @check_period_end
      AND range_end >= @check_period_start

P.S。更新@check_period_end&amp; @check_period_start,单引号中的相关开始和结束日期。

答案 1 :(得分:0)

您可以通过此查询获取示例中的句号

SELECT DATEDIFF(day,'2008-06-05','2008-08-05')

现在,如果你想通过单个查询在你的例子中创建输出表,那就太复杂了。首先尝试使用带有上述查询的视图然后获取数据...尝试这个,如果你得到任何错误然后问这里..至少先尝试..

答案 2 :(得分:0)

我不确定......我认为此声明有效(未经测试)

SELECT T01.[Creditors name],
(SELECT SUM() FROM TABLEA T02 WHERE DATEDIFF(day,T02.[Due date], GetDate())) BETWEEN -1 AND 31 AND T01.[Creditors name] = T02.[Creditors name])  AS [0-30 Days],
(SELECT SUM() FROM TABLEA T03 WHERE DATEDIFF(day,T02.[Due date], GetDate())) BETWEEN -30 AND 61 AND T01.[Creditors name] = T03.[Creditors name]) AS [31-60 Days],
(SELECT SUM() FROM TABLEA T04 WHERE DATEDIFF(day,T02.[Due date], GetDate())) BETWEEN -60 AND 91 AND T01.[Creditors name] = T04.[Creditors name]) AS [61-90 Days],
(SELECT SUM() FROM TABLEA T05 WHERE DATEDIFF(day,T02.[Due date], GetDate())) > 90 AND T01.[Creditors name] = T05.[Creditors name]) AS [Over 90 Days],
SUM(T01.[Outstanding Amt]) AS [Amt Due]
FROM TABLEA T01
GROUP BY T01.[Creditors name]