我有一个包含以下列的表,我正在尝试创建一个视图以创建报表,我需要获取特定类的已完成小时数的总和但是使用特定的过滤器:
FK_CLASS_ID
我需要找到每个班级(FK_CLASS_ID
)为每个班级(CLASS_DAY
)完成的小时数的SUM(目前我已将其过滤到ID 27452进行测试),同时为每个班级应用以下过滤器( CLASS_OUTCOME
):
CLASS_DATE
必须是不同的| PK_CLASS_DAYS_ID | FK_MAIN_ID | FK_CLASS_ID | Hrs |
|------------------|-------------|--------------|------|
| 1 | 27452 | 137 | 32 |
| 2 | 27452 | 2 | 8 |
| 3 | 27452 | 48 | 12 |
必须以“*”SELECT
t1.CLASS,
SUM(class_hours) as Hrs,
GROUP_CONCAT('D',classes_days.class_day) as DaysList,
main.FULLNAME
FROM
classes t1
INNER JOIN classes_days ON classes_days.FK_CLASS_ID = t1.CLASS_ID
INNER JOIN main ON main.PK_MAIN_ID = classes_days.FK_MAIN_ID
WHERE
main.PK_MAIN_ID = 27452
GROUP BY FK_CLASS_ID
ORDER BY CLASS
必须是最新的,但仍具有前两个条件。结果视图应如下所示:myObj.ErrorString = (string) (object) num + (object) " file(s) failed to import. Run the Import Report for more information.";
我试图完成此任务的最远的是以下选择声明:
num
答案 0 :(得分:0)
对于您想要完成的任务,您需要使用所需的求和查询过滤联接,并根据检索到的记录集提供所需条件的加入。
根据您提供的查询和所需结果,它应该如下所示:
SELECT
`t1`.`CLASS`,
SUM(`class_hours`.`HOURS`) AS `Hrs`,
GROUP_CONCAT('D', `class_hours`.`CLASS_DAY` ORDER BY `class_hours`.`CLASS_DAY`) AS `DaysList`,
`main`.`FULLNAME`
FROM `classes` AS `t1`
INNER JOIN (
#Filter the total hours by student, class, and day
SELECT `class_dates`.`FK_MAIN_ID`, `class_dates`.`CLASS_DAY`, `class_dates`.`FK_CLASS_ID`, SUM(`class_dates`.`HOURS`) as `HOURS`
FROM (
#Filter Most Recent Days beginning with star, by most recent date
SELECT `classes_days`.*
FROM `classes_days`
WHERE `classes_days`.`OUTCOME` LIKE '*%'
ORDER BY `CLASS_DATE` DESC
) AS `class_dates`
GROUP BY `class_dates`.`FK_MAIN_ID`, `class_dates`.`CLASS_DAY`, `class_dates`.`FK_CLASS_ID`
) AS `class_hours`
ON `class_hours`.`FK_CLASS_ID` = `t1`.`CLASS_ID`
INNER JOIN `main`
ON `main`.`PK_MAIN_ID` = `class_hours`.`FK_MAIN_ID`
GROUP BY `class_hours`.`FK_MAIN_ID`, `class_hours`.`FK_CLASS_ID`
ORDER BY `FULLNAME`, `CLASS`;
导致:
| CLASS | Hrs | DaysList | FULLNAME |
|---------|-----|-------------|----------|
| History | 8 | D1 | Joe |
| Math | 32 | D1,D2,D4 | Joe |
| Science | 12 | D1,D2 | Joe |
| Math | 10 | D1,D2 | Mike |
示例:http://sqlfiddle.com/#!9/d5828/1
表的原始查询是最高查询。子查询连接示例是底部查询结果。删除了PK_MAIN_ID
条件以显示其针对多个条目
请记住,MySQL GROUP BY
+ ORDER BY
并不总能产生所需的结果,应该使用子查询进行过滤,子查询在连接子查询中进行了演示,以便获得最新结果以*。