Doubt in query SQL group by and nulls

2

Fiddle to test queries: link

  

Let's say I have a table like that.

+-------------+-------------+------------------+-------------+
|     Cod     |  Provincia  |    Cliente       |     tlfn    |
+-------------+-------------+------------------+-------------+
|   00001     |  Barcelona  |   Cliente1       |  666123123  |
+-------------+-------------+------------------+-------------+
|   00002     |  Pais Vasco |   Cliente2       |  666345345  |
+-------------+-------------+------------------+-------------+
|   00003     |  Madrid     |   Cliente3       |  952819252  |
+-------------+-------------+------------------+-------------+
|   00004     |  Valencia   |   Cliente4       |  895182952  |
+-------------+-------------+------------------+-------------+
|   00005     |  Barcelona  |   Cliente5       |  666213213  |
+-------------+-------------+------------------+-------------+
  

And I ask you this question.

SELECT Provincia, COUNT(*)
FROM tabla
WHERE tlfn LIKE '666%'
GROUP BY Provincia
  

The result of this query would be

+------------+-------+
| Barcelona  |   2   |
+------------+-------+
| Pais vasco |   1   |
+------------+-------+

But I also want to reflect that in Madrid and in Valencia there is no client whose phone starts with strong> 666

How can I reflect that in the result? How do I get this result?

+------------+-------+
| Barcelona  |   2   |
+------------+-------+
| Pais vasco |   1   |
+------------+-------+
|  Valencia  |   0   |
+------------+-------+
|  Madrid    |   0   |
+------------+-------+
    
asked by Aritzbn 09.03.2018 в 08:29
source

1 answer

2

So, very quickly, this occurs to me.

SELECT tabla.Provincia,count(conDatos.Provincia)
FROM tabla  LEFT OUTER JOIN  
 (select distinct Provincia from tabla WHERE tabla.Telefono LIKE '666%') conDatos   ON
conDatos.provincia=tabla.provincia
group by tabla.Provincia
order by Provincia

link

    
answered by 09.03.2018 / 09:26
source