Sql server中每日销售总和

时间:2013-12-09 13:04:26

标签: sql-server

我在sql server中有一个像这样的表

userid username sale date 
 1       azad    50  12/07/2013 
 2       akash   40  12/07/2013
 3       sushil  30  12/07/2013
 4       pankaj  20  12/07/2013
 5       akash   40  12/07/2013
 6       sushil  30  12/07/2013
 9       pankaj  20  12/07/2013

现在我想要所有用户的销售日期总和但是从上次销售中我想要输出的所有用户

ClosingBalance

140

此结果基于所有四个用户的最后一个条目

2 个答案:

答案 0 :(得分:1)

WITH T AS
(
SELECT *,
       ROW_NUMBER() OVER (PARTITION BY username ORDER BY date DESC, id DESC) AS RN
FROM  Balances
)
SELECT SUM(sale)
FROM T
WHERE RN=1

SQL Fiddle

答案 1 :(得分:-1)

$sum_sale= mysql_query('SELECT sum(sale) FROM `TABLE` AND '2011-12-09' BETWEEN startdate AND enddate;');
$sum_sales_total = mysql_fetch_array($sum_sales);

这应该会帮助你。