2

I'm having a hard time putting some queries together.

SELECT `part_num`, COUNT(`part_num`) AS `total` 
    FROM `job_sheet` 
    WHERE `qty`!=0 AND `completion`=1 
    GROUP BY `part_num` 
    ORDER BY `total` DESC 
    LIMIT 10

This basically pulls up the most common part number and it shows how many times it appears in the 'total' variable. I also limited to the top 10 part number in this case. These parts number also have a quantity column 'qty' that shows how many parts there are:

part_num | qty 

1001     | 1000
1004     | 200 
1003     | 360 
1001     | 1000
1001     | 1000

In this case my first statement would show that part number 1001 would appear three times, item number 4 would appear once etc., etc. My issue is that I would like to add up the qty column along with my statement in order to show that item 1001 appears 3 times with a 'qty' sum of 3000.

Any ideas on how to do this ?

3 Answers 3

3

You don't need to use DISTINCT as you are already using a GROUP BY.

To show the sum you simply need to add the field with the SUM() function.

SELECT part_num, COUNT(part_num) AS total, SUM(qty) as total_qty 
    FROM job_sheet 
    WHERE qty!=0 AND completion=1 
    GROUP BY part_num 
    ORDER BY total DESC 
    LIMIT 10;
Sign up to request clarification or add additional context in comments.

Comments

3

Use DISTINCT

SELECT DISTINCT part_num, COUNT(part_num) AS total 
FROM job_sheet WHERE qty!=0 AND completion=1 
GROUP BY part_num 
ORDER BY total DESC 
LIMIT 10

1 Comment

This won't work since I'm always missing the 'qty' column so I can add up the total 'qty' for every part. I need to be able to add up the 'qty' for everytime my part number appears. In the example above, for item 1001, I would need a separate column that shows the sum, which in this case would have been 1000+1000+1000 = 3000.
0

@JohnConde's answer is more efficient (+1), but just in case you wanted to do it in PHP:

$totals= array();

foreach ($data as $v) {
    isset($totals[$v['part_num']])) ?
        $totals[$v['part_num']] += $v['qty'] :
        $totals[$v['part_num']] = $v['qty'];   
}

1 Comment

Yea lol , PHP always works, but I really wanted to avoid using too much PHP to solve my issues. I had done it in PHP, but I find it gets too many when write classes...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.