Count Of items, Count of Items Passed and percentage passed

J

Jay Balapa

Hello,

Underlying table has the following fields and values
Barcode Item Pass
1000 x YES
1001 x YES
1002 x NO
1003 x NO
1004 y YES
1005 y YES
1006 y NO


Iam trying to create a summary resultset which has the follwing-

Item, [Total # of items], [# of Items Passed], [Percentage Passed]
x 4 2 50%
y 3 2 66%



I know I have to group by item and use the count to get the total number of
items. But Iam baffled on how to get # items passed and Percentage.

Can this be accomplished in a single statement?

Any help will be greatly appreciated.

-Jay
 
A

Anith Sen

Lookup the PIVOT operator in SQL 2005.

For some solutions applicable in SQL 2000, refer to KBA (
support.microsoft.com ) : 175574.
 
M

markc600

select Item,
count(*) as [Total # of items],
sum(case when Pass='YES' then 1 else 0 end) as [# of Items
Passed],
cast(sum(case when Pass='YES' then 100 else 0 end)/count(*) as
varchar(10))+'%' as [Percentage Passed]
from mytable
group by Item
 
M

Mike C#

CREATE TABLE #items (Barcode VARCHAR(4),
Item VARCHAR(10),
Pass VARCHAR(3))

INSERT INTO #items (Barcode, Item, Pass)
SELECT '1000', 'x', 'YES'
UNION SELECT '1001', 'x', 'YES'
UNION SELECT '1002', 'x', 'NO'
UNION SELECT '1003', 'x', 'NO'
UNION SELECT '1004', 'y', 'YES'
UNION SELECT '1005', 'y', 'YES'
UNION SELECT '1006', 'y', 'NO'

SELECT i.Item, COUNT(i.Item) Total_Items,
(
SELECT COUNT(Barcode)
FROM #items
WHERE Pass = 'YES'
AND i.Item = Item
) Total_Passed,
((
SELECT COUNT(Barcode)
FROM #items
WHERE Pass = 'YES'
AND i.Item = Item
) * 100 / COUNT(i.Item)) Percentage_Passed
FROM #items i
GROUP BY i.Item

DROP TABLE #items
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top