我想进行特定查询以对有关 2 个表的特定信息进行分组

I want to make a specific query to group specific information about 2 tables

所以我有 2 个表格,如下所示:

Factory
| name | timeoperating | operatedpieces |

Pieces
| serial | piecetype | unit (foreign key referencing factory.name) |

"Pieces"中的"Unit"是引用"Factory"中的"Name"的外键。 我想进行一个查询,其中包含 "name"、"timeoperating"、"operated pieces",然后是另外 9 列,其中包含每种类型(从 P1 到 P9)中具有 [=29= 的片段的数量] 或 "name" 已连接。当然是每行一个名字。

我尝试了很多不同的方法,但我从来没有得到 return 任何与我想要的类似的东西的查询,这可能吗?

输出(第一行):

| factory.name | factory.timeoperating | factory.operatedpieces |
  count(pieces.piecetype) where piecetype=P1 and unit=factory.name | 
  (then other 8 columns like the last one 
   but with piecetype = Px where X is the column number)

啊我怕我没说清楚...

您可以使用 9 "scalar subqueries".

获取该数据

例如:

select 
 f.name,
 f.timeoperating,
 f.operatedpieces,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 1) as c1,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 2) as c2,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 3) as c3,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 4) as c4,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 5) as c5,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 6) as c6,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 7) as c7,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 8) as c8,
 (select count(*) from pieces p where p.unit = f.name and p.piecetype = 9) as c9
from factory f