I had Collection Table for Agents

Agentid         logintime             AmountReceived

1        2013/10/01 00:10:10         10000
1        2013/10/01 17:23:10         200
1        2013/10/01 00:30:41         3000
2        2013/10/02 05:10:52         1000
3        2013/10/02 09:10:25         2000 
3        2013/10/03 10:10:18         2000
2        2013/10/03 13:10:35         7000 

I want a query that should display the output as

Agentid    Amount  Rank
  1         13200    1
  2         8000     2
  3         4000     3

Displaying UI:

agentID : 1

Today:   13200 (Today amount yesturady amount should be place in this month)
Month:   Need to display month total amount(30 days amount last month amount in this year)
Year :   Need to display year total amount(12 months amount)
有帮助吗?

解决方案

Try this:

SELECT Agentid,SUM(AmountReceived) as Amount,@rownum := @rownum + 1 AS Rank
FROM TableName,(SELECT @rownum := 0) r
GROUP BY AgentID
ORDER BY SUM(AmountReceived) DESC

Result:

AGENTID  AMOUNT     RANK
1        13200      1
2        8000       2
3        4000       3

See result in SQL Fiddle.

EDIT:

For year-wise and month-wise result:

SELECT Agentid,year(logintime) as Year,monthname(logintime) as Month,SUM(AmountReceived) as Amount,@rownum := @rownum + 1 AS Rank
FROM TableName,(SELECT @rownum := 0) r
GROUP BY AgentID,year(logintime),monthname(logintime)
ORDER BY SUM(AmountReceived) DESC

Result:

AGENTID   YEAR   MONTH      AMOUNT  RANK
1         2013   October    13200   1
2         2013   October    8000    2
3         2013   October    4000    3

Result in SQL Fiddle.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top