问题
This query return number of rows where Sum of Product's Quantity is equal to 0 and Product Name is 'XYZ'. But I want same result for each products. For example if I remove product name from where clause so it will bring SUM of every product where quantity is 0. I want it to return separately for each products. Products may increase in future. I have to first check how many distinct products are there in CustomerProduct table and then need to query same things for each product. How can I do that. Title might not is perfect, Please suggest/correct if it required to.
select Count(*) From
(select distinct VI.Name, Cp.ProductName
FROM VendorInfo VI inner join VendorTrading VT on VI.Id = VT.VendorId inner join CustomerProducts CP on VT.Id = CP.VendorTradingId
Where VT.Tradedate = '2015-12-25' and CP.ProductName = 'XYZ'
GROUP BY VI.Name, Cp.ProductName, CP.ProductQuantity
HAVING SUM( CP.ProductQuantity ) = 0) as x
回答1:
Affan, can you add tsql script to create the tables with some data, so it is easier for us to assist. However if you simplify the query then you can get each product and vendor with zero ProductQuantity
select VI.Name, Cp.ProductName, SUM( CP.ProductQuantity )
FROM VendorInfo VI
inner join VendorTrading VT on VI.Id = VT.VendorId
inner join CustomerProducts CP on VT.Id = CP.VendorTradingId
Where VT.Tradedate = '2015-12-25'
GROUP BY VI.Name, Cp.ProductName
HAVING SUM( CP.ProductQuantity ) = 0
来源:https://stackoverflow.com/questions/35686459/how-to-get-total-number-of-rows-within-subquery-for-multiple-conditions