显示字段中的总计值

时间:2011-03-04 16:18:18

标签: php select field

下午好。我在想是否有可能在表格中显示所选字段的总和或总计,并与日期有关:

例如,我想知道每个月我酒店的啤酒总消费量。

我在这里有关于服务的表格:

[services_id[pk],
customer_id[fk],
date_in,date_out,room_type,room_number,
extra_ref,
extra_bed,extra_snack,
extra_beer,extra_softdrinks,
extra_pillows,extra_breakfast,
extra_snack_q,
extra_beer_q,
extra_softdrinks_q,
extra_pillows_q,
extra_breakfast_q]
你能告诉我怎样才能得到它。 提前谢谢:

-renz

2 个答案:

答案 0 :(得分:0)

SELECT SUM(beer_amount) as monthly_beer_amount
FROM [DATABASE].[TABLE] 
WHERE beer_sold_date BETWEEN '20110201' AND '20110228'

[额外信息]

此外,我认为组织此表的最佳方法是将此表分成几个其他表。将客户信息存储在第一个表格中,例如

[customer_id, customer_name, date_in, date_out, room_type, room_number]. 
1, Bob, 20110101, 20110110, big, 200
2, Joe, 20110101, 20110110, small, 202
....

还有一个名为room_items的表,其中包含以下内容,

[id, item_name]
1, BEER
2, BED
3, SNACK
...

然后另一个名为room_purchases的表将具有以下内容,

[customer_id, purchase_id, amount, date....]
1, 1, 10, 20110101
2, 3, 5, 20110101
3, 1, 9, 20110101
....

这可以帮助你在所有三个表上进行连接,并且它们会以这种方式更加规范化。

SELECT SUM(t2.amount) as beer_amount
FROM customers as t1 
LEFT JOIN room_purchases as t2 ON t1.customer_id = t2.customer_id
WHERE t2.purchase_id = 1 AND t2.date BETWEEN 20110101 AND 20110131

答案 1 :(得分:0)

SELECT DATE_FORMAT(date_in,"%m-%Y") AS month,SUM(extra_beer) AS beers
FROM your_table
GROUP BY month

这将返回如下内容:

02-2011 | 43
03-2011 | 52

如果您想根据日期限制查询,只需在WHERE

之前添加GROUP BY约束