【问题标题】:SQL query to retrieve WooCommerce orders grouped by state用于检索按状态分组的 WooCommerce 订单的 SQL 查询
【发布时间】:2013-11-07 19:02:56
【问题描述】:

我试图从 Wordpress/WooCommerce 数据库中检索的是按美国各州分组的订单列表,其中包含每个州的订单总额和订单税。

所以我得到的最接近的是我写的这个查询:

SELECT meta_key, meta_value 
FROM wp_posts 
LEFT OUTER JOIN wp_postmeta ON wp_posts.ID=wp_postmeta.post_id 
WHERE post_type = "shop_order" 
AND (
meta_key = "_billing_state" 
OR meta_key = "_order_tax" 
OR meta_key = "_order_total"
) 
ORDER BY ID ASC

然后它返回:

meta_key         meta_value
_billing_state   NJ
_order_tax       0.21
_order_total     3.21
_billing_state   NJ
_order_tax       1.75
_order_total     26.70
_billing_state   IA
_order_tax       6.79
_order_total     103.54
_billing_state   PA
_order_tax       1.82
_order_total     27.72

...等等。

我真正需要回报的是:

state  order_tax_sum  order_total_sum
NJ     1.96           29.91
IA     6.79           103.54
PA     1.82           27.72

非常感谢所有帮助!

【问题讨论】:

    标签: sql wordpress woocommerce


    【解决方案1】:

    试试这样的:

    select
        state,
        sum(order_tax_sum),
        sum(order_total_sum)
    from (
        select
            (select meta_value from wp_postmeta pm1 where p.ID = pm1.post_id and meta_key = "_billing_state") as state,
            (select meta_value from wp_postmeta pm2 where p.ID = pm2.post_id and meta_key   = "_order_tax") as order_tax_sum,
            (select meta_value from wp_postmeta pm3 where p.ID = pm3.post_id and meta_key   = "_order_total") as order_total_sum
        from
            wp_posts AS p
        WHERE post_type = "shop_order"
    ) A
    group by A.state
    

    警告 - 完全未经测试,但基本思想(在 select 语句中加入)应该是合理的

    【讨论】:

    • 感谢您的回复。我尝试了您的确切查询并在第 2 行收到 1064 错误,因此我正在尝试解决它。你有什么明显的问题吗?
    • 您使用的是 mySQL?我从未使用过它(到目前为止,sql server 和 oracle),所以可能不允许使用括号?不幸的是,我没有可以真正测试该查询的数据库实例。如果这不起作用,您可以发布表结构吗?我做了一些可能不正确的假设。
    • 是的,它在 MySQL 上。我刚刚删除了所有方括号,现在它抱怨第 10 行“来自 wp_posts p”
    • 我添加了 AS 并在第 9 行末尾删除了多余的逗号。现在我得到“'where 子句'中的“未知列'p.post_id'” - 我仍然可以发布结构如果这会有所帮助!到目前为止,谢谢!
    • doh,那是我的错,看起来 ID 在一个表中被称为 post_id,但在另一个表中只是 ID。我修复了上述查询(以及我遇到的其他错误)
    猜你喜欢
    • 2022-11-01
    • 2016-12-09
    • 2011-11-02
    • 2019-12-20
    • 2017-05-24
    • 2016-07-31
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    相关资源
    最近更新 更多