1

What type of sql query would I use to turn the following;

|  ID  |  SERIAL  |  LCN  | INITLCN |
|------|----------|-------|---------|
|  1   |    A     |  A1   |         |
|  2   |    B     |  A2   |         |
|  3   |    C     |  A3   |   A1    |
|  4   |    D     |  A4   |   A2    |
|  5   |    E     |  A5   |   A1    |
|------|----------|-------|---------|

into a result similar to this;

|  ID  |  COUNT  |
|------|---------|
|  1   |    2    |
|  2   |    1    |
|------|---------|

Using my low SQL skills, I have managed to write the below query however it is extremely slow;

select
  a.id,
  count (b.id) as parent
from assets a 
left join assets b
  ON (a.lcn = b.initlcn)
group by a.id
order by a.id;
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Dan
  • 303
  • 1
  • 13

3 Answers3

0
select
t1.ID,
t1.LCN,
COUNT(*)
from
Table1 t1
INNER JOIN Table1 t2 ON t1.LCN = t2.INITLCN
GROUP BY t1.LCN

See it working live in an sqlfiddle.

fancyPants
  • 50,732
  • 33
  • 89
  • 96
0

maybe two table join is not nesecerry . try this

select 
a.id
,b.cnt
from assets a
join (
 select 
 initlcn
 count(1) cnt
 from assets
 group by initlcn
)
b on (a.lcn=b.initlcn)
Wasif
  • 522
  • 2
  • 6
gufeng
  • 26
  • 2
0

you can test following query also -

I have checked the execution plan for your posted query and the following query and I am getting good difference between both -

SELECT t_1.Id, t_2.Cnt
  FROM Assets t_1,
       (SELECT Initlcn, COUNT(*) Cnt FROM Assets GROUP BY Initlcn) t_2
 WHERE t_1.Lcn = t_2.Initlcn
pratik garg
  • 3,282
  • 1
  • 17
  • 21