1

我想找到每天最畅销的三种产品,并将它们与销量一起展示。

但是,如果有多个产品共享相同数量的销售额,我只想知道有多少产品获得了这个排名。

我有两张桌子

Products:
+-----+---------+
| Pid | Product |
+-----+---------+
|  1  | Moon    |
|  2  | Sun     |
|  3  | Venus   |
|  4  | Mars    |
+-----+---------+

SalesRows:
+-----+---------+------------+
| Pid | No_sold | Sales_date |
+-----+---------+------------+
|  1  |    1    | 2013-01-01 |
|  2  |    5    | 2013-01-01 |
|  3  |    2    | 2013-01-01 |
|  2  |    2    | 2013-01-01 |
+-----+---------+------------+

应该给:

+------+--------------+-------+
| Rank | Product      | Sales |
+------+--------------+-------+
|  1   | Sun          |   7   |
|  2   | Venus        |   2   |
|  3   | Moon         |   1   |
+------+--------------+-------+

然而这个销售数据:

SalesRows:
+-----+---------+------------+
| Pid | No_sold | Sales_date |
+-----+---------+------------+
|  1  |    1    | 2013-01-01 |
|  2  |    5    | 2013-01-01 |
|  3  |    2    | 2013-01-01 |
|  2  |    2    | 2013-01-01 |
|  4  |    1    | 2013-01-01 |
+-----+---------+------------+

应该给:

+------+--------------+-------+
| Rank | Product      | Sales |
+------+--------------+-------+
|  1   | Sun          |   7   |
|  2   | Venus        |   2   |
|  3   | *2 products* |   1   |
+------+--------------+-------+

任何建议如何解决这最后一部分?

4

2 回答 2

2

此查询可能会对您有所帮助。

SELECT @rownum := @rownum + 1 rownum, 
       t.* 
  FROM (SELECT @rownum:=0) r, 
       (select case when indicator = 1 then Product
else concat( indicator, ' Products') end as Product, sales from (Select *, count(sales) as indicator from (SELECT Product,SUM(No_sold) AS sales FROM SalesRows
JOIN Products ON Products.Pid = SalesRows.Pid
WHERE Sales_date = curdate()
GROUP BY SalesRows.Pid ) a group by sales Order by sales desc) a) t
于 2013-03-01T08:43:30.123 回答
0

尝试这个 :

SELECT Product,SUM(No_sold) AS sales FROM SalesRows 
LEFT JOIN Products ON Products.Pid = SalesRows.Pid
WHERE Sales_date = '".$today."'
GROUP BY Pid
于 2013-03-01T07:26:16.850 回答