Sohail
Sohail

Reputation: 574

SQL count is not upto my desired result

I have two different table Products and ProductImages:

SELECT COUNT(p.productid) AS product_count, COUNT(pi.imageid) AS image_count  
FROM [Products] p, [ProductImages] pi  
WHERE p.productid=126 AND pi.productid=126;  

Above query is giving me the mulitplication of both counts in each COUNT. Please guide me where I am wrong and Can I do it with single select query.

Upvotes: 1

Views: 142

Answers (3)

Suraj Singh
Suraj Singh

Reputation: 4059

SELECT  COUNT(DISTINCT p.productid) AS product_count ,
        COUNT(DISTINCT pi.imageid) AS image_count
FROM    [Products] p ,
        [ProductImages] pi
WHERE   p.productid = 126
        AND pi.productid = 126 ;  

Upvotes: 0

Elvin
Elvin

Reputation: 2291

You can get this in two rows

SELECT COUNT(p.productid) As Count
FROM [Products] p
WHERE p.productid=126
UNION All
SELECT COUNT(pi.imageid) As Count
FROM  [ProductImages] pi 
WHERE pi.productid=126;

OR you can do this without UNION ALL

SELECT 
(SELECT COUNT(p.productid) As Count 
From [Products] p WHERE p.productid=126) ) as t1,
(SELECT COUNT(pi.imageid) As Count 
FROM  [ProductImages] pi WHERE pi.productid=126) as t2

Upvotes: 4

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Try This by subquery

SELECT COUNT(p.productid) AS product_count,(Select COUNT(pi.imageid) AS image_count  [ProductImages] pi  Where pi.productid=126; ) FROM [Products] p  WHERE p.productid=126 

Upvotes: 1

Related Questions