这里我在parent_sku列上使用group by。这是我的查询及其结果。
SELECT
domain,
parent,
parent_name,
parent_sku,
SUM(qty) AS sales,
SUM(gross) AS revenue,
SUM(net) AS net_revenue,
SUM(refund_qty) AS returns,
created_at
FROM report_byproducts_name
GROUP BY parent_sku
ORDER BY sales DESC
LIMIT 50
但我想优先考虑域名。就像我优先考虑itusthaves域一样,它应该将结果作为domain = themusthaves and parent = 450212
给出相同的组。
目前,我总是收到domain=tmhde
和parent=325227
注意:请忽略created_at列
任何建议都将受到赞赏
由于
我在这里添加SQL Fiddle
答案 0 :(得分:0)
我认为您需要聚合更多列,然后加入到您的表中以获取相关的非聚合列
select domain,
parent,
parent_name,parent_sku,
sumsales,sumrevenue,sumnet_revenue,sumreturns
from report_byproducts_name
Join
(
SELECT
max(parent) maxparent,
parent_sku aggsparent_sku,
SUM(sales) AS sumsales,
SUM(revenue) AS sumrevenue,
SUM(net_revenue) AS sumnet_revenue,
SUM(returns) AS sumreturns
FROM report_byproducts_name
GROUP BY parent_sku
) aggs on aggs.maxparent = parent and aggs.aggsparent_sku = parent_sku;
+--------------+--------+--------------------------------+------------+----------+-------------------+-------------------+------------+
| domain | parent | parent_name | parent_sku | sumsales | sumrevenue | sumnet_revenue | sumreturns |
+--------------+--------+--------------------------------+------------+----------+-------------------+-------------------+------------+
| themusthaves | 450212 | Pailletten Damaged Jeans Grijs | 311 | 350 | 13692.89013671875 | 11360.31005859375 | 1 |
+--------------+--------+--------------------------------+------------+----------+-------------------+-------------------+------------+
1 row in set (0.00 sec)
我可以建议您将浮点字段更改为十进制(10,2)。
答案 1 :(得分:0)
您可以通过创建temp
表来实现此目的。您可以这样做:
WITH temp AS
(
SELECT
parent_sku,
SUM(qty) AS sales,
SUM(gross) AS revenue,
SUM(net) AS net_revenue,
SUM(refund_qty) AS returns,
created_at
FROM report_byproducts_name
GROUP BY parent_sku
)
SELECT * FROM report_byproducts_name
WHERE parent_sku IN (SELECT parent_sku FROM temp) AND domain = 'themusthaves'
您可以在Where子句中给予优先权。
答案 2 :(得分:0)
感谢您的支持。我可以使用如下的子查询获得预期的结果。我不知道方式是否正确,但我在这里发布我的答案,通过该答案,我可以得到预期的结果。通过我将等待更好的建议,以获得预期的结果。
SELECT
(SELECT domain FROM report_byproducts_name WHERE domain='themusthaves' AND parent_sku=rbn.parent_sku) as domain,
(SELECT parent FROM report_byproducts_name WHERE domain='themusthaves' AND parent_sku=rbn.parent_sku) as parent,
parent_name,
parent_sku,
SUM(sales) as sales,
SUM(revenue) as revenue,
SUM(net_revenue) as net_revenue,
SUM(returns) as returns,
created_at
FROM report_byproducts_name rbn
GROUP by parent_sku
ORDER BY sales DESC
LIMIT 50
预期结果为SQL Fiddle