我正在尝试构建一个返回聚合销售数据的查询。我当前的查询返回一个类似于这样的表:
----------------------------------
| DATE | SKU | TOTAL |
----------------------------------
| 2014-11-10 | AV155_A | 209.00 |
| 2014-11-10 | AV155_B | 627.00 |
| 2014-11-10 | AV155_C | 279.00 |
| 2014-11-10 | AV155 | 279.00 |
| 2014-11-10 | AV1556_A | 209.00 |
| 2014-11-10 | AV1556_B | 627.00 |
| 2014-11-10 | AV1556_C | 279.00 |
| 2014-11-10 | AV1556 | 279.00 |
但是,我希望汇总的总数不是每个SKU的总数,而是将每个SKU与相同的“父sku”匹配。在这个例子中,我想要两个结果,一个聚合'AV1555'的总和一个聚合'AV1556'的总和。该表应如下所示:
-----------------------------------
| DATE | SKU | TOTAL |
-----------------------------------
| 2014-11-10 | AV1555 | 1394.00 |
| 2014-11-10 | AV1556 | 1394.00 |
我目前使用的查询如下所示:
select
DATE_FORMAT(created_on, '%m-%d-%Y') as date,
sku,
SUM(price) as total
FROM order_items
WHERE created_on between FROM_UNIXTIME(1415577600) AND NOW()
GROUP BY MONTH(created_on), DAY(v.created_on), order_item_sku;
答案 0 :(得分:2)
我认为你想要的是substring_index()
:
select DATE_FORMAT(created_on, '%m-%d-%Y') as date,
substring_index(sku, '_', 1) as sku_prefix
SUM(price) as total
FROM order_items
WHERE created_on between FROM_UNIXTIME(1415577600) AND NOW()
GROUP BY date(v.created_on), substring_index(sku, '_', 1);
您还应该在group by
中包含年份(通过包括整个日期来完成)。今天可能不需要它,但从现在起三到四周它可能会有用。
答案 1 :(得分:0)
您可以在LEFT(sku,6)上汇总
select
DATE_FORMAT(created_on, '%m-%d-%Y') as date,
LEFT(sku,6),
SUM(price) as total
FROM order_items
WHERE created_on between FROM_UNIXTIME(1415577600) AND NOW()
GROUP BY MONTH(created_on), DAY(v.created_on), LEFT(sku,6);
如果你的sku可以是可变长度,你可以使用
select
DATE_FORMAT(created_on, '%m-%d-%Y') as date,
LEFT(sku,LEN(sku)-2),
SUM(price) as total
FROM order_items
WHERE created_on between FROM_UNIXTIME(1415577600) AND NOW()
GROUP BY MONTH(created_on), DAY(v.created_on), LEFT(sku,LEN(sku)-2);
然而,你有一些非儿童skus的例子,这使得它变得更加困难......