我有几张table:
m_foldercommittee:
| id_folder| id_committe|意见|
| --|--|--|
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 1 |
m_folder:
| id_folder| id_committe|
| --|--|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
m_schedule:
| id_schedule|类型表|id_folder|
| --|--|--|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
m_committee:
| 身份证委员会|日期委员会|
| --|--|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
现在,查询看起来像这样:
select c.date_committee,
sum(1) as total,
sum(if(fc.opinion= 1 , 1, 0)) as nb_folder,
sum(if(fc.opinion= 2 , 1, 0)) as nb_folder_favorable,
sum(if(fc.opinion= 3 , 1, 0)) as nb_folder_principe,
from m_foldercommittee fc
INNER JOIN m_committee c ON c.id_committee = fc.id_committee
INNER JOIN m_folder mf ON mf.id_folder = fc.id_folder
where EXISTS(SELECT NULL
FROM m_schedule sch
WHERE sch.type_schedule = 1
AND sch.id_folder = fc.id_folder
AND ((sch.beginning_date >= '2022-08-25' AND sch.ending_date <= '2023-09-25')
OR (sch.beginning_date < '2022-08-25' AND sch.ending_date >= '2022-08-25')
OR (sch.beginning_date <= '2023-09-25' AND sch.ending_date >= '2023-09-25')
))
group by fc.id_committee
字符串
并返回类似这样的内容:
| 日期委员会|总|nb_folder| nb_folder_favorable| nb_folder_principe|
| --|--|--|--|--|
| 2023-08-25 2023-08-25 2023-08-25| 13 | 12 | 1 | 0 |
| 2023-09-15 2023-09-15| 24 | 20 | 4 | 0 |
| 2023-09-25 2023-09-25| 91 | 88 | 3 | 0 |
我想要的是插入一个新列,它是type_schedule = 1的sum,但我不想成为sum(1)的一部分。
以下是我到目前为止写的:
select c.date_committee,
sum(1) as total,
sum(if(sch.type_schedule= 1 , 1, 0)) as nb_beverage,
sum(if(fc.opinion= 1 , 1, 0)) as nb_folder,
sum(if(fc.opinion= 2 , 1, 0)) as nb_folder_favorable,
sum(if(fc.opinion= 3 , 1, 0)) as nb_folder_principe,
from m_foldercommittee fc
INNER JOIN m_committee c ON c.id_committee = fc.id_committee
INNER JOIN m_folder mf ON mf.id_folder = fc.id_folder
INNER JOIN m_schedule sch ON sch.id_folder = fc.id_folder
where EXISTS(SELECT NULL
FROM m_schedule sch
WHERE sch.type_schedule = 1 and sch.id_folder = fc.id_folder
AND ((sch.beginning_date >= '2022-08-25' AND sch.ending_date <= '2023-09-25')
OR (sch.beginning_date < '2022-08-25' AND sch.ending_date >= '2022-08-25')
OR (sch.beginning_date <= '2023-09-25' AND sch.ending_date >= '2023-09-25')
))
group by fc.id_committee
型
它的工作,但问题是,第二个版本的查询返回值是完全不同的第一个版本的查询.如何排除的结果sum(if(sch.type_schedule= 1 , 1, 0)) as nb_beverage
从总和(1),所以新版本的查询返回完全相同的结果作为第一个,但一个新的列 nb_beverage?
1条答案
按热度按时间t9aqgxwy1#
下面是@jarlh在评论中建议的使用子查询的效果。我希望这会有用:
字符串