简体   繁体   中英

SQL Join self referencing table

I have 2 tables as Classification and Company_Classification in my DB. The structure below is just an example and I have given my code further below.

Classification
ClassId
ClassName
Parent_Id

Company_Classification
LinkId
CompanyId
ClassId

I need to count the number of companies which falls under parent Classification and group it by parent classification. So, companies that falls under each child classification will be counted under its parent classification.

SELECT
  TOP (100) PERCENT dbo.CLASSIFICATION.class_name,
  COUNT(dbo.COMPANY_CLASSIFICATION.Company_ID) AS Count
FROM
  dbo.CLASSIFICATION
INNER JOIN dbo.COMPANY_CLASSIFICATION 
  ON dbo.CLASSIFICATION.class_id = dbo.COMPANY_CLASSIFICATION.Class_ID
WHERE     (dbo.CLASSIFICATION.parent_id = 0)
GROUP BY dbo.CLASSIFICATION.class_name
ORDER BY dbo.CLASSIFICATION.class_name

I am not sure I have phrased my question correctly. So, Basically how can I twaek the query to get companies records grouped by parent classification (including it child records)?

Thanks,

On second thought, it looks like you might have a hierarchy structure.

;WITH ClassificationHierarchy AS
(
    SELECT   ClassId
            ,ClassName
            ,RootParent = ClassId
    FROM Classification
    WHERE Parent_Id = 0
    UNION ALL
    SELECT   CS.ClassId
            ,CS.ClassName
            ,RootParent
    FROM ClassificationHierarchy    CH
    JOIN Classification             CS  ON CH.ClassId = CS.Parent_Id
)
SELECT RootParent, COUNT(*)
FROM ClassificationHierarchy    CH
JOIN Company_Classification     CC  ON CC.ClassId = CH.ClassId
GROUP BY RootParent

You need to join a second time to the classification table:

select cparent.class_name, count(*)
from Company_Classification cc join
     Classification c
     on cc.Classid = C.ClassId join
     Classification cparent
     on c.parent_id = cparent.classid
group by cparent.class_name

Because you use the TOP clause there? if you want to count how many there are for each classification must remove the top.

If what you want is the first 100 companies might make sense, but then you must create a subquery that has the top and these together with the main query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM