一个SQL查询,用于从另一个表中获取来自不同表的项目数

时间:2015-06-16 15:35:02

标签: sql sql-server count

我有5张表

- Project(PK Project_ID), 
- Bottles (PK Bottle_ID, FK Project_ID), 
- Plastics (PK Plastic_ID, FK Project_ID), 
- Glasses (PK Glass_ID,FK Project_ID) and 
- Cups (PK Cup_ID, FK Project_ID)

如何获得一个SQL查询来返回每个项目的瓶子,塑料,眼镜和杯子的数量,其中一个项目有多个瓶子,塑料,眼镜和杯子?

4 个答案:

答案 0 :(得分:3)

select p.project_id, count(distinct bottle_id), count(distinct plastic_id), count(distinct glass_id), count(distinct cup_id)
from project p
left join bottles b on p.project_id = b.project_id
left join plastics pl on p.project_id = pl.project_id
left join glasses g on p.project_id = g.project_id
left join cups c on p.project_id = c.project_id
group by p.project_id

答案 1 :(得分:2)

Create table Project (Project_ID int )
Create table Bottles ( Bottle_ID int,  Project_ID int)
Create table Plastics ( Plastics_ID int,  Project_ID int)
Create table Glasses ( Glasses_ID int,  Project_ID int)
Create table Cups ( Cups_ID int,  Project_ID int)

insert into Project (Project_ID) values (1)
insert into Bottles (Bottle_ID,Project_ID) values (1,1)
insert into Bottles (Bottle_ID,Project_ID) values (2,1)
insert into Bottles (Bottle_ID,Project_ID) values (3,1)
insert into Plastics (Plastics_ID,Project_ID) values (1,1)
insert into Plastics (Plastics_ID,Project_ID) values (2,1)
insert into Glasses (Glasses_ID,Project_ID) values (1,1)
insert into Glasses (Glasses_ID,Project_ID) values (2,1)
insert into Cups (Cups_ID,Project_ID) values (1,1)
insert into Cups (Cups_ID,Project_ID) values (2,1)

select distinct p.Project_ID, 
(select COUNT(*) from Bottles where p.Project_ID=Project_ID) Bottles ,
(select COUNT(*) from Plastics where p.Project_ID=Project_ID) Plastics ,
(select COUNT(*) from Glasses where p.Project_ID=Project_ID) Glasses ,
(select COUNT(*) from Cups where p.Project_ID=Project_ID) Cups 
from Project p

答案 2 :(得分:1)

SELECT P.Project_ID, COUNT(B.BOTTLE_ID) AS BOTTLECOUNT,
COUNT(L.PLASTIC_ID) AS PLASTICCOUNT,
COUNT(G.GLASSES_ID) AS GLASSCOUNT,
COUNT(C.CUP_ID) AS CUPCOUNT
FROM PROJECT AS P
INNER JOIN BOTTLES B
ON P.PROJECT_ID=B.PROJECT_ID
INNER JOIN PLASTIC L
ON P.PROJECT_ID=L.PROJECT_ID
INNER JOIN GLASSES G
ON P.PROJECT_ID = G.PROJECT_ID
INNER JOIN CUPS C
ON P.PROJECT_ID=C.PROJECT_ID
GROUP BY P.PROJECT_ID, BOTTLE_ID, PLASTIC_ID, GLASSES_ID, CUP_ID
ORDER BY PROJECT_ID

答案 3 :(得分:1)

您的意思是希望您显示唯一的项目ID,其中至少有> = 1瓶,> = 1塑料,> = 1玻璃,> = 1个杯子?如果是这样,您可以编写一个这样的查询,它根据FK(ProjectID)连接所有表,并按ProjectID连接:

SELECT p.ProjectID
    ,COUNT(DISTINCT (b.Bottle_ID)) 'CountBottles'
    ,COUNT(DISTINCT (p.Plastic_ID)) 'CountPlastic'
    ,COUNT(DISTINCT (g.Glass_ID)) 'CountGlass'
    ,COUNT(DISTINCT (c.Cup_ID)) 'CountCup'
FROM Project p
INNER JOIN Bottles b ON p.projectID = b.projectID
INNER JOIN Plastics pl ON pl.projectID = p.projectID
INNER JOIN Glasses g ON g.projectID = p.projectID
INNER JOIN Cups c ON c.projectID = p.projectID
GROUP BY p.ProjectID