简体   繁体   English

SQL 平均每天花费的钱

[英]SQL average money spent per day

I would like to get some help in writing SQL query for the table below.我想在为下表编写 SQL 查询时获得一些帮助。 The table represents how much students spent at a food court on a given date.该表显示了学生在特定日期在美食广场花费的金额。 With this table, write an SQL query that calculates the number of days between the first and last date of money spent by each student and the money spent per day in this timespan.使用此表,编写一个 SQL 查询,计算每个学生从第一天到最后一天花费的钱与在此时间跨度内每天花费的钱之间的天数。

Student_id            Date      Money Spent($)
    1              01.01.2017      15.13
    2              03.01.2017      22.94
    3              03.01.2017      37.50
    2              01.02.2017      44.26
    2              08.04.2017      52.62
    3              09.08.2017      34.67
    1              02.09.2017      43.87
    3              04.11.2017      12.67

Try this尝试这个

SELECT Student_id,MIN([date]) mindate, MAX([date]) maxdate,SUM(MoneySpent) TotalSpent,
        SUM(MoneySpent)/DATEDIFF ( MIN([date]) , MAX([date]) ) MoneySpentPerDay 
        FROM StudentExpenses
        GROUP BY Student_id

SELECT student_id,AVG(spent) FROM `students` GROUP BY student_id;

Well, that's gonna need a GROUP BY per student. 好吧,那将需要每个学生一个GROUP BY。 Oh yes Sir. 哦,是的,先生。
And a MIN & MAX of the date for the first & last. 以及第一个和最后一个日期的MIN&MAX。

The money spend per day you ask? 您每天花费的钱是多少?
Ah, that could be the SUM of the spend money divided by the COUNT of the DATEDIFF between the MIN & MAX date. 嗯,这可能是支出金额的总和除以MIN和MAX日期之间的DATEDIFF的COUNT。
Or maybe it's just an AVG of the money spend? 还是只是花钱的AVG?

Not a clear answer? 不清楚的答案?

Hey, don't blame me! 嘿,别怪我! I never went to those food courts. 我从没去过那些美食广场。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM