Frage

I have two tables like this.

A   B  
1   12  
2   13  
3   12  
4   13  
5   15  


B   C
12  APPLE  
13  ORANGE  
14  MANGO  
15  BANANA  

I need output as below...

count(A)  B  C  
2         12 APPLE  
2         13 ORANGE  
0         14 MANGO  
1         15 BANANA  

I have written the query using joins but I am stuck at displaying the count as zero in case of empty value.

War es hilfreich?

Lösung

Use a left join to get the values of table2 even if there are no records for them in table1

select T2.B, T2.C, count(T1.A)
from table2 T2
left join table1 T1 on T1.B = T2.B
group by T2.B, T2.C

Andere Tipps

Try this:

SELECT COUNT(T1.A) as Cnt,T2.B,T2.C
FROM Table2 T2 LEFT JOIN
     Table1 T1 ON T1.B=T2.B
GROUP BY T2.B,T2.C

Result:

CNT   B     C
2     12    APPLE
1     15    BANANA
0     14    MANGO
2     13    ORANGE

See result in SQL Fiddle.

Just to give you another option. You don't need a join, as you only want to show table2 records along with another value which you can get in a sub-query.

select (select count(*) from table1 where table1.B = table2.B) as cnt, B, C
from table2
order by B;

There are other ways to do it (using subquery), but I would use this following one:

-- SETUP
CREATE TABLE #TABLE1 (A INT, B INT);
CREATE TABLE #TABLE2 (B INT, C CHAR(10));

INSERT #TABLE1
SELECT 1, 12 UNION ALL
SELECT 2, 13 UNION ALL
SELECT 3, 12 UNION ALL
SELECT 4, 13 UNION ALL
SELECT 5, 15

INSERT #TABLE2
SELECT 12, 'APPLE'  UNION ALL
SELECT 13, 'ORANGE' UNION ALL
SELECT 14, 'MANGO'  UNION ALL
SELECT 15, 'BANANA'

-- query
SELECT COUNT(qty.A), dsc.B, dsc.C
FROM      #TABLE2 dsc
LEFT JOIN #TABLE1 qty ON (dsc.B = qty.B)
GROUP BY dsc.B, dsc.C
ORDER BY dsc.B, dsc.C;
DECLARE @TABLE1 TABLE (A INT,  B INT)
INSERT INTO @TABLE1 VALUES  
(1,   12),  
(2,   13),  
(3,   12),  
(4,   13),  
(5,   15)  

DECLARE @TABLE2 TABLE (B INT,  C VARCHAR(20))
INSERT INTO @TABLE2 VALUES  
(12,'APPLE'),  
(13,'ORANGE'),  
(14,'MANGO'),  
(15,'BANANA')




SELECT t2.C
       ,ISNULL(COUNT(t1.B), 0) total_Count
FROM @TABLE2 t2 LEFT JOIN @TABLE1 t1
ON t2.B = t1.B
GROUP BY t2.C   


C      total_Count
APPLE   2
BANANA  1
MANGO   0
ORANGE  2
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top