我有三个表(这些是相关列):
Table1
bookingid, person, role
Table2
bookingid, projectid
Table3
projectid, project, numberofrole1, numberofrole2
Table1.role可以采用两个值:“role1”或“role2”。
我想要做的是在表1中显示哪些项目不具有正确数量的角色。每个角色应该有的角色数量见表3.
例如,如果Table1包含这三行:
bookingid, person, role
7, Tim, role1
7, Bob, role1,
7, Charles, role2
和表2
bookingid, projectid
7, 1
和表3
projectid, project, numberofrole1, numberofrole2
1, Test1, 2, 2
我希望结果显示项目 Test1 没有正确数量的 role2s 。
老实说,这样的事情有点超出我的能力范围,所以我愿意接受最佳方法的建议。我正在使用sqlite和php(它只是一个小项目)。我想,一旦我得到了我的结果,我可以在最后用php做些什么,但我想知道是否有更好的方法来使用sqlite。
我开始做这样的事情:
SELECT project, COUNT(numberofrole1) as "Role"
FROM Table1
JOIN Table2
USING (projectid)
JOIN Table3
USING (bookingid)
WHERE role="role1"
GROUP BY project
但我无法弄清楚如何将返回的值作为“角色”与从numberofrole1获得的值进行比较
感谢任何帮助。
答案 0 :(得分:0)
试试这个:
Select * From Table3 t3
Where (Select Count(*) From Table1 t1r1
Join Table2 t2r1 On t2r1.bookingid = t1r1.bookingid
Where t2r1.projectid = t3.ProjectId
And role = 'role1') <> numberofrole1
Or
(Select Count(*) From Table1 t1r2
Join Table2 t2r2 On t2r2.bookingid = t1r2.bookingid
Where t2r2.projectid = t3.ProjectId
And role = 'role2') <> numberofrole2
甚至更好,如果它有效......(尝试一下)
Select * From Table3 t3
Where Exists
(Select * From Table1 t1r1
Join Table2 t2r1
On t2r1.bookingid = t1r1.bookingid
Where t2r1.projectid = t3.ProjectId
Group By Role
Having Sum(Case Role When 'role1' Then 1 Else 0 End)
= t3.numberofrole1
And Sum(Case Role When 'role2' Then 1 Else 0 End)
= t3.numberofrole2 )
答案 1 :(得分:0)
SELECT * FROM
(
SELECT
projectid,
role,
CASE WHEN role = 'role2' THEN numberofrole2 DEFAULT numberofrole1 END numRequired,
COUNT(*) numPresent
FROM Table1
JOIN Table2 ON Table1.bookingid = Table2.bookingid
JOIN Table3 ON Table2.projectid = Table3.projectid
GROUP BY projectid, role
)
WHERE numRequired > numPresent
答案 2 :(得分:0)
尝试类似的东西:
SELECT
projectid,
numberofrole1,
numberofrole2,
SUM(role='role1') as actual_numberofrole1,
SUM(role='role2') as actual_numberofrole2
FROM table3
JOIN table2
USING (projectid)
JOIN table1
USING (bookingid)
GROUP BY projectid
HAVING numberofrole1 <> actual_numberofrole1
OR numberofrole2 <> actual_numberofrole2