【发布时间】:2022-01-09 17:51:33
【问题描述】:
我想在一个查询中从三个 SQL 表中选择信息。
一个示例可能是以下设置。
tblFriends
id | idmother | dayBirth
--------------------------
1 | 1 | 09/09/21
2 | 2 | 09/09/21
3 | 3 | 11/09/21
4 | 3 | 11/09/21
5 | 4 | 07/09/21
... | ... | ...
tblMothers
id | name
---------------
1 | Alice
2 | Samantha
3 | Veronica
4 | Maria
... | ...
tblIsAssignedParty
idMother | codeParty | price
------------------------------
1 | 231 | 15
2 | 645 | 28
3 | 164 | 33
... | ... | ...
我想要一个能提供以下信息的查询:
dayBirth | weekDay | totalFriendsForParty | totalFriendsForPartyPercent | totalFriendsNoParty | totalFriendsNoPartyPercent
-----------------------------------------------------------------------------------------------------------------------------
07/09/21 | Tuesday | 0 | 0 | 1 | 0.??
09/09/21 | Thursday | 2 | 0.?? | 0 | 0
11/09/21 | Saturday | 2 | 0.?? | 0 | 0
注意:
- dayBirth = 简单的出生日期;我需要按此日期分组的朋友
- weekDay = dayBirth name
- totalFriendsForParty = 将参加聚会的朋友;我们知道母亲是否安排了派对
- totalFriendsForPartyPercent = 朋友的百分比,占参加聚会的朋友总数的百分比
- totalFriendsNoParty = 不参加聚会的朋友;我们知道母亲是否没有指定派对
- totalFriendsNoPartyPercent = 朋友的百分比,占不参加聚会的朋友总数的百分比
我需要根据他们的母亲是否参加聚会来确定朋友的数量。我尝试在单个查询中选择多个语句,但以下代码不起作用:
SELECT
(SELECT distinct dayBirth, TO_CHAR(dayBirth, 'DAY') from tblFriends) as firstSecondColumn,
(SELECT dayBirth, count(*) from tblFriends
where idMother IN (
SELECT f.idMother
from tblFriends f
left join tblIsAssignedParty iap
on f.idMother = iap.idMother
where iap.codeParty is not null)
group by dayBirth) as thirdColumn,
(SELECT TRUNC(count(*) / count(thirdColumn.id) , 2) from tblFriends) as quarterColumn,
(SELECT dayBirth, count(*) from tblFriends
where idMother IN (
SELECT f.idMother
from tblFriends f
left join tblIsAssignedParty iap
on f.idMother = iap.idMother
where iap.codeParty is not null)
group by dayBirth) as fifthColumn,
(SELECT TRUNC(count(*) / count(fifthColumn.id) , 2) from tblFriends) as sixthColumn,
order by dayBirth
对这个有什么建议吗?我努力学习,尽我所能:-(
编辑:我无法添加插入,因为它是文件上传,但我可以添加表创建的近似值。
创建表:
CREATE TABLE tblFriends
(
id NUMBER(*,0),
idMother CHAR(10 CHAR),
CONSTRAINT PK_FRIEND PRIMARY KEY (id, idMother),
CONSTRAINT FK_IDMOTHER FOREIGN KEY (idMother)
REFERENCES tblMothers (id),
dayBirth DATE CONSTRAINT NN_DAY NOT NULL
)
CREATE TABLE tblMothers
(
id CHAR(10 CHAR) CONSTRAINT PK_MOTHER PRIMARY KEY (id),
name VARCHAR2(20 CHAR) CONSTRAINT NN_MNAME NOT NULL
)
CREATE TABLE tblIsAssignedParty
(
idMother CHAR(10 CHAR),
codeParty CHAR(10 CHAR),
CONSTRAINT PK_ASSIGNED PRIMARY KEY (idMother, codeParty),
CONSTRAINT FK_ASSIGNEDMOTHER FOREIGN KEY (idMother)
REFERENCES tblMothers (id),
CONSTRAINT FK_ASSIGNEDPARTY FOREIGN KEY (codeParty)
REFERENCES tblParties (codeParty),
price DECIMAL(10,2)
)
【问题讨论】:
-
请edit 您的问题包含minimal reproducible example 与:
CREATE TABLE表的语句;样本数据的INSERT语句足以为您的预期数据生成 complete 输出;以及关于列含义以及如何将它们连接在一起以获得预期输出的英文(非代码)描述。您的列codeparty、price和name似乎与问题无关。目前还不清楚你如何计算谁是朋友。为什么朋友表中有dateOfBirth列,它与聚会日期有何关系? -
我无法完全提供您的要求,表格的列比这多得多。我已经更好地解释了结果并附加了创建以查看这些表是如何相关的。