question

fashraf avatar image
fashraf asked

Find the percentage with multiple Join.

MainTable HospitalId City Data 1 1 20 1 1 10 2 2 50 3 3 100 Hospital HospitalId, Staff 1 5 2 30 3 10 CityId City 1 Delhi 2 New York 3 Mumbai I need to find the percentageform the city ResultTable City Staff Total Percentage Delhi 10 30 New York 30 50 Mumbai 10 100 I try doing the cound but It dosnt work with the group by clause. data column is the sales.I need to find the sales Percentage related to each city. I have tried this but I am not getting the desired result. SELECT C.City ,COUNT(M.City)*MAX(H.Staff) Staff ,SUM(M.Data)Total_Percentage FROM City C JOIN MainTable M ON M.City=C.CityId JOIN Hospital H ON H.HospitalId=M.HospitalId GROUP BY C.City
sql-server-2008tableinner join
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Kev Riley avatar image Kev Riley ♦♦ commented ·
Your query does give you the result that you wanted - why do you think it does not work?
0 Likes 0 ·
ThomasRushton avatar image ThomasRushton ♦♦ commented ·
What is your desired result?
0 Likes 0 ·

1 Answer

·
ThomasRushton avatar image
ThomasRushton answered
Do you mean something like this? DECLARE @MainTable TABLE (HospitalID INT, CityID INT, Data INT); DECLARE @Hospital TABLE (HospitalID INT, Staff INT); DECLARE @City TABLE (CityID INT, City VARCHAR(50)); INSERT INTO @MainTable VALUES (1,1,20),(1,1,10),(2,2,50),(3,3,100); INSERT INTO @Hospital VALUES (1,5),(2,30),(3,10); INSERT INTO @City VALUES (1,'Delhi'),(2,'New York'),(3,'Mumbai'); SELECT C.City, COUNT(M.CityId) * MAX(H.Staff) * 100 / SUM(COUNT(M.CityId) * MAX(H.Staff) ) OVER (PARTITION BY 1) FROM @City AS C JOIN @MainTable AS M ON M.CityID = C.CityID JOIN @Hospital AS H ON H.HospitalID = M.HospitalID GROUP BY C.City;
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.