Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count in Query 400 not passing correctly

I Have a table that has order data like this: Table Order_Detail and Item_Master are joined by Item# We want to report on order number, Order_Detail table:

Order#     Item#              

1234       IPhone6 
1234       IPhone5
1234       Battery

join Item_Master:

Item#            Item_type    Desc

IPhone6          Phone        Smartphone
IPhone5          Phone        Smartphone

Now we only want order numbers, that have only one Item-Type = Phone. We are only interested in types Phone. I tried using Query/400 and doing a count on order# which = Phone, and then taking only the counts = 1. But this does bring in some orders that have more than one phone type = Phone, in our example here we would not want this order.

like image 552
Paul K. Avatar asked Nov 27 '25 05:11

Paul K.


2 Answers

Your question is a little confusing. Are you looking to get a count of order numbers where Item_Type = 'Phone'? If so the follwoing should work for you:

SELECT COUNT(DISTINCT OrderNum) AS OrderNumCount
FROM Order_Detail o
INNER JOIN Item_Master i ON o.ItemNum = o.ItemNum
WHERE Item_type = 'Phone'

Or are you after only the orders that have only one record from the item table linked. If so then you may want:

SELECT o.OrderNum
FROM Order_Detail o
INNER JOIN Item_Master i ON o.ItemNum = o.ItemNum
WHERE Item_type = 'Phone'
GROUP BY o.OrderNum
HAVING COUNT(*) = 1 
like image 90
Linger Avatar answered Nov 29 '25 18:11

Linger


You could try something like

SELECT o.OrderNum 
FROM 
  Order_Detail o 
INNER JOIN 
  Item_Master m
On o.ItemNum = m.ItemNum
WHERE m.Item_Type = 'Phone'
GROUP BY o.OrderNum
HAVING COUNT(*) = 1 
like image 33
Ian Kenney Avatar answered Nov 29 '25 19:11

Ian Kenney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!