我将举两个例子,第一个有效,第二个有我想做的事:
SELECT P.ProjName, D.update_date, SUM(E.pass), SUM(E.fail)
FROM execution AS E INNER JOIN (
daily AS D INNER JOIN project AS P ON D.project_ID = P.ID )
ON E.daily_ID = D.ID
WHERE D.project_id = 25 AND D.update_date = (
SELECT MAX(update_date) FROM daily WHERE project_id = 25; )
GROUP BY P.ProjName, D.update_date;
这适用于个别项目。它给出了给定项目最近一天的通过和失败总数(此处为25)。我想使用WHERE IN子句获取一组项目。例如(但不起作用):
SELECT P.ProjName, D.update_date, SUM(E.pass), SUM(E.fail)
FROM execution AS E INNER JOIN (
daily AS D INNER JOIN project AS P ON D.project_ID = P.ID )
ON E.daily_ID = D.ID
WHERE D.project_id IN (25,26,28,29,30,31)
GROUP BY P.ProjName, D.update_date
HAVING MAX(D.update_date);
这将导致每个项目的每个日期都被拉出。涉及3个表,'project'由'daily'链接,由'execution'链接。因此,对于每个项目,每天都有多个数据,每天都有多个执行数据。我意识到HAVING MAX可能需要进行比较,但对于什么?也许修改后的JOIN会有所帮助。
谢谢, 基思
答案 0 :(得分:8)
在不知道数据库的情况下尝试这样做有点棘手,但试试这个:
SELECT P.ProjName, D.update_date, SUM(E.pass), SUM(E.fail)
FROM execution AS E INNER JOIN (
daily AS D INNER JOIN project AS P ON D.project_ID = P.ID )
ON E.daily_ID = D.ID
WHERE D.project_id IN (25,26,28,29,30,31) AND D.update_date = (
SELECT MAX(update_date) FROM daily WHERE project_id = D.project_id)
GROUP BY P.ProjName, D.update_date;
我真的不知道这是否接近你想要的任何东西。
答案 1 :(得分:0)
您没有指定特定的DBMS,那么这个(未经测试的)SQL代码应该在多大程度上与DBMS无关:
SELECT P.ProjName,
DesiredProjectUpdateDate.MaxUpdateDate,
SELECT SUM(pass) AS PassSum
FROM execution
WHERE daily_ID=D.ID,
SELECT SUM(fail) AS FailSum
FROM execution
WHERE daily_ID=D.ID
FROM
( -- This derived table helps you get the correct records from the daily table
SELECT D.project_ID, MAX(D.Update_date) AS MaxUpdateDate
FROM daily AS D
GROUP BY D.project_ID
WHERE D.project_ID IN (25,26,28,29,30,31)
) As DesiredProjectUpdateDate
JOIN daily AS D
ON D.project_ID=DesiredProjectUpdateDate.project_ID AND
D.Update_date=DesiredProjectUpdateDate.MaxUpdateDate
JOIN project AS P
ON P.ID = DesiredProjectUpdateDate.ProjectId
如果你有任何进一步的问题,请告诉我们。
答案 2 :(得分:0)
问题是您需要一个select,它返回每个项目的update_date的最大值。
试试这个:
SELECT P.ProjName, D.update_date, SUM(E.pass), SUM(E.fail)
FROM execution AS E INNER JOIN (
daily AS D INNER JOIN project AS P ON D.project_ID = P.ID )
ON E.daily_ID = D.ID
WHERE D.project_id IN (25,26,28,29,30,31)
AND D.update_date > ALL
(SELECT update_date FROM
daily AS D2
WHERE D.ID=D2.ID -- I am assuming that daily.ID is the primary key
AND ISNULL(D.update_date, '9999 DEC 31') <> D2.update_date)
GROUP BY P.ProjName, D.update_date;
我经常写这样的查询,它们比使用MAX
聚合函数更快并且工作得很好。
编辑:抱歉,我忘记删除您现在多余的HAVING MAX...
行。我的坏!