我正在运行一个非常简单的MySQL查询并尝试按销售价值排序数据...数据库中的列设置为十进制(16,2)但是当数据返回时它没有排序任何订单。
这是我的代码:
$query = "
SELECT *
, SUM(sale_value)
FROM sale
WHERE week_no = $today
GROUP
BY user_id
ORDER
BY sale_value DESC
";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['user_id']. " = £". $row['SUM(sale_value)'];
echo "<br />";
}
以下是我得到的结果:
Total 14 = £2195.77
Total 62 = £865.01
Total 52 = £2989.53
Total 42 = £2689.47
Total 51 = £894.51
Total 48 = £962.09
Total 39 = £1161.43
Total 33 = £1341.49
Total 1 = £5989.57
Total 8 = £4937.48
Total 59 = £1377.70
Total 32 = £3063.06
Total 41 = £1937.82
Total 60 = £2981.01
Total 53 = £1050.21
Total 46 = £1836.05
Total 57 = £310.43
Total 19 = £2534.92
Total 5 = £1946.01
Total 56 = £471.00
Total 7 = £865.00
Total 2 = £754.30
有人能发现我做错了吗?
答案 0 :(得分:2)
您在匹配的行中按任意值排序,而不是总和。为列添加别名并使用:
SELECT *, SUM(sale_value) as total_sale_value
FROM sale
WHERE week_no = ".$today."
GROUP BY user_id
ORDER By total_sale_value DESC;
顺便说一下,select *
与group by
一起使用是一个非常非常非常糟糕的主意。您应该明确列出用于定义每个聚合组的列:
SELECT user_id, SUM(sale_value) as total_sale_value
FROM sale
WHERE week_no = ".$today."
GROUP BY user_id
ORDER By total_sale_value DESC;
答案 1 :(得分:0)
您应该order by SUM(sale_value)
而不是sale_value