2

工作

JobId, JobName  

工作详情

JobDetailId, JobId, AcctNum, PerformDate

一个Job有很多JobDetails链接JobId

对于某些JobNames,(JobeName1,JobeName2)我想要一个列表,其中只有一个JobDetailPerformdate在过去 6 个月内。

对于上述标准,我应该得到两条记录。什么是正确的 SQL 语句?

我已经做到了这一点,而不仅仅是得到正确的陈述。

SELECT 
    COUNT(J.JobId) 
FROM 
    Job J  
WHERE 
    J.JobName IN ('Doc1', 'Doc2')
GROUP BY 
    J.JobName

[编辑]
SQL Server 2005

[编辑2]

SELECT 
    J.JobName, JD.AcctNum 
FROM 
    Job J  
JOIN JobDetail JD ON J.JobId = JD.JobId
WHERE 
    J.JobName IN ('DOC1', 'DOC2')
GROUP BY 
    J.JobName

该声明正在产生:

J.JobId 在选择列表中无效...未包含在聚合函数中...

[EDIT3]
http://sqlfiddle.com/#!3/3ef21/1/0

我想要 Doc1 和 DOC2 的 PerformDate 的最新 AcctNum。

因此,从 SQLFIDDLE 中的数据,我应该为每个 JobName 取回 2 ROWS。

[EDIT4]
我的预期数据是 JobDetail 表中的 * 行:
JobDetailId 1
jobDetailId 3

4

2 回答 2

4

干得好:

SELECT COUNT(J.JobId) FROM Job J  
INNER JOIN JobDetails D ON J.JobId = D.JobId
WHERE J.JobName IN ('Jobname1', 'Jobname2') 
AND D.PerformDate >= DateAdd(mm, -6, getdate())
GROUP BY J.JobName

我已经用 TSQL (SQL Server) 编写了这个。对于其他 DBMS,您必须使用DateAdd(mm, -6, getdate()).

更新:为和选择最新AcctNum的。DOC1DOC2

选择 D.JobID, Acctnum from
    JobDetail D 内连接
    (
     SELECT J.JOBID, MAX(PerformDate) as LatestPerformDate FROM Job J
     INNER JOIN JobDetail D ON J.JobId = D.JobId
     J.JobName IN ('DOC1', 'DOC2')
     按 J.JobID 分组
    ) D.JobID 上的 X = X.JobID
    D.PerformDate = X.LatestPerformDate

更新 2:何时DOC2可以在表中出现两次Job不同的JobID.

Select D.JobID, Acctnum from 
JobDetail D Inner Join Job J on J.JobID = D.JobID
Inner join
(
 SELECT J.JOBname, MAX(PerformDate) as LatestPerformDate FROM Job J  
 INNER JOIN JobDetail D ON J.JobId = D.JobId
 WHERE J.JobName IN ('DOC1', 'DOC2')
 group by j.jobname
) X on J.JobName = X.JobName
And D.PerformDate = X.LatestPerformDate

问题中 sqlfiddle 中发布的输入数据的输出:

JOBID   ACCTNUM
--------------------
 1      1235
 4      1238
于 2013-07-30T03:55:20.290 回答
2
SELECT j.*, d.*
FROM Job j
JOIN (SELECT JobId, MAX(PerformDate) maxDate
      FROM JobDetail
      WHERE PerformDate > DATEADD(mm, -6, GETDATE())
      GROUP BY JobId) md
ON j.JobId = md.JobId
JOIN JobDetail d
ON d.JobId = md.JobId AND d.PerformDate = md.maxDate
WHERE j.JobName IN ('DOC1', 'DOC2');

小提琴

于 2013-07-30T03:55:29.410 回答