选择两个日期之间的列的总和

时间:2013-07-22 03:11:47

标签: sql sql-server-2008-r2

我希望select每天p_amount Payments p_date @startdate @enddate CREATE TABLE [dbo].[tbl_Payments]( [p_id] [bigint] IDENTITY(100000,1) NOT NULL, [p_amount] [int] NOT NULL, [p_status] [tinyint] NOT NULL, [p_date] [datetime] NOT NULL, [p_creditor] [int] NOT NULL, [p_debtor] [int] NOT NULL, [p_type] [int] NOT NULL, CONSTRAINT [PK_tbl_Payments] PRIMARY KEY CLUSTERED ) sum day --------------------------------- 30 2013-07-01 40 2013-07-02 ... .... 10 2013-07-19 {{1}}

{{1}}

我想跟随

{{1}}

2 个答案:

答案 0 :(得分:2)

我不熟悉sql-server查询,但你问题的查询是像这样的东西

SELECT    sum(p_amount) as sum, CONVERT(date, getdate()) as day
FROM      [YourTable]
WHERE     [YourDate] BETWEEN [day1] AND [day2] group by day

答案 1 :(得分:1)

尝试

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, p_date)) [date],
       SUM(p_amount) [sum]
  FROM tbl_Payments
 WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, p_date)) BETWEEN '20130701' AND '20130731'
 GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, p_date))

示例输出:

|                        DATE | SUM |
-------------------------------------
| July, 01 2013 00:00:00+0000 |  22 |
| July, 02 2013 00:00:00+0000 |  30 |
| July, 03 2013 00:00:00+0000 |  35 |

这是 SQLFiddle 演示