我有一个包含以下字段的表:
我正在尝试创建一个查询,该查询将按年度的每周对所有销售进行分组,然后在我的页面上拆分每周的amount_sales总和。
示例:
week 1 = $26.00
week 2 = $35.00
week 3 = $49.00
等。我正在使用此查询,但它不起作用:
SELECT SUM(`amount_sale`) as total
FROM `sales`
WHERE `payment_type` = 'Account'
GROUP BY WEEK(`the_date`)
答案 0 :(得分:31)
如果将the_date
存储为整数,则首先需要使用FROM_UNIXTIME
函数将其转换为日期时间:
SELECT SUM(`amount_sale`) as total
FROM `sales`
WHERE `payment_type` = 'Account'
GROUP BY WEEK(FROM_UNIXTIME(`the_date`))
<强>更新强>:
此外,您可能希望输出周数,
SELECT CONCAT('Week ', WEEK(FROM_UNIXTIME(`the_date`))) as week_number,
SUM(`amount_sale`) as total
FROM `sales`
WHERE `payment_type` = 'Account'
GROUP BY WEEK(FROM_UNIXTIME(`the_date`))
答案 1 :(得分:4)
尝试在查询中选择周,例如:
SELECT SUM(`amount_sale`) as total, WEEK(`the_date`) as week
FROM `sales`
WHERE `payment_type` = 'Account'
GROUP BY week ORDER BY week ASC
如果您有几周的周期,您也可以从the_date
中选择年份并订购该年份,例如
ORDER BY week ASC, year ASC
答案 2 :(得分:0)
带上您的date
和get the week
:
SELECT DATEPART( wk, getdate()) --this is assuming SQL server
,然后是group
。
答案 3 :(得分:0)
由于the_date
是一个unix时间戳,WEEK
函数将无效。相反,你可以这样做:
GROUP BY周(FROM_UNIXTIME(the_date))
请记住,这不会很好,因为该函数需要应用于您查询的表中的每一行。