Skip to content

Instantly share code, notes, and snippets.

@acip
Last active March 16, 2022 19:09
Show Gist options
  • Save acip/08f06da9563effac27271c3ec2210843 to your computer and use it in GitHub Desktop.
Save acip/08f06da9563effac27271c3ec2210843 to your computer and use it in GitHub Desktop.
Retrieve customers details from Woocommerce, including total spent amount (only completed orders)
SELECT
B.meta_value AS first_name,
C.meta_value AS last_name,
K.user_email AS email,
D.meta_value AS phone,
ROUND(SUM(L.meta_value)) AS total_orders,
H.meta_value AS city,
G.meta_value AS state,
F.meta_value AS country,
I.meta_value AS postcode
FROM
mthld_posts AS A
LEFT JOIN mthld_postmeta B ON
A.id = B.post_id AND B.meta_key = '_billing_first_name'
LEFT JOIN mthld_postmeta C ON
A.id = C.post_id AND C.meta_key = '_billing_last_name'
LEFT JOIN mthld_postmeta D ON
A.id = D.post_id AND D.meta_key = '_billing_phone'
LEFT JOIN mthld_postmeta F ON
A.id = F.post_id AND F.meta_key = '_billing_country'
LEFT JOIN mthld_postmeta G ON
A.id = G.post_id AND G.meta_key = '_billing_state'
LEFT JOIN mthld_postmeta H ON
A.id = H.post_id AND H.meta_key = '_billing_city'
LEFT JOIN mthld_postmeta I ON
A.id = I.post_id AND I.meta_key = '_billing_postcode'
LEFT JOIN mthld_postmeta J ON
A.id = J.post_id AND J.meta_key = '_customer_user'
LEFT JOIN mthld_postmeta L ON
A.id = L.post_id AND L.meta_key = '_order_total'
LEFT JOIN mthld_users K ON
J.meta_value = K.ID
WHERE
A.post_type = 'shop_order' AND A.post_status = 'wc-completed' and K.user_email > ""
GROUP BY
K.ID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment