• Resolved M.Danz

    (@mdanz-1)


    I’m using woocommerce and i’m attempting my own custom query. What i want to be returned is the top categories by sales. For example if the category(taxonomy) ship has 64 sales, car has 45 sales & boat has 23 sales. Then what should be returned is ship, car & boat in that order. Here is my attempt at the query:

    global $wpdb;
    
        $result = $wpdb->get_results ( "SELECT wp_term_taxonomy.taxonomy, sum(v1.meta_value) FROM wp_posts
        INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
        INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
        INNER JOIN wp_postmeta v1 ON (wp_posts.ID = v1.post_id) AND v1.meta_key='total_sales'
        WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'product' AND wp_term_taxonomy.taxonomy = 'product_cat'
        GROUP BY wp_term_taxonomy.taxonomy
        ORDER BY sum(v1.meta_value) DESC
     " );
    
    print_r($result);

    Here is the query not in wordpress format:

    SELECT category, sum(sales)
    FROM table
    GROUP BY category
    ORDER BY sum(sales) DESC

    How do i solve this? I only get 1 result in the array when it should return multiple results, where did i go wrong?

Viewing 1 replies (of 1 total)
  • Thread Starter M.Danz

    (@mdanz-1)

    Here is the query i used to get it working

    SELECT wp_terms.name, sum(v1.meta_value) FROM wp_posts
        INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
        INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
    	INNER JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
    	INNER JOIN wp_postmeta v1 ON (wp_posts.ID = v1.post_id) AND v1.meta_key LIKE 'total_sales'
    	WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'product' AND wp_term_taxonomy.taxonomy = 'product_cat'
    	GROUP BY wp_terms.name
    	ORDER BY sum(v1.meta_value) DESC
Viewing 1 replies (of 1 total)
  • The topic ‘Query only returning 1 result’ is closed to new replies.