How to write Sql Query to show Number of Names based on one Product Id. For example in this example: For ProductId - 263, Count(Name) = 3
I would like to see
263 3
264 2
265 10
266 0 (if null)
How to write Sql Query to show Number of Names based on one Product Id. For example in this example: For ProductId - 263, Count(Name) = 3
I would like to see
263 3
264 2
265 10
266 0 (if null)
SELECT productid, COUNT(*)
FROM products
GROUP BY productid
It's not an exact answer, but it will return the number of occurrences of the productid for each unique productid. It may help you find your result.
Assuming you have a table of products, then you want a left join
:
select p.productid, count(pn.productid)
from products p left join
productnames pn
on p.productid = pn.productid
group by p.productid;
Pang.
I have written an answer using a CTE that will give you the count of all the names for each product that can easily be changed to COUNT the DISTINCT names.
;WITH CTE_DISTINCT_NAMES
AS (SELECT --DISTINCT
/* Uncomment "DISTINCT" above
to include duplicate names
in the COUNT
*/
ProductId
, Name
FROM TABLE1
)
SELECT T.ProductId
, COUNT(ISNULL(T.Name,'')) AS [COUNT(Name)]
FROM CTE_DISTINCT_NAMES AS T
GROUP BY T.ProductId
Try this solution:
SELECT
PRODUCT_ID AS PID,
COALESCE(COUNT(NAME), 0) AS CNT
FROM YOUR_TABLE
GROUP BY PRODUCT_ID