SQL仅从连接表返回第一个匹配项

时间:2016-06-07 15:03:56

标签: sql greatest-n-per-group filemaker

我有一个简单的一对多作业和状态表。作业可以在处理过程中在状态中来回循环,因此作业可以具有多个特定状态的实例。但是,我需要一份关于该工作的报告,因为它从头到尾只触及特定状态的第一个实例。

我最初构造的语句将返回我需要的数据但是对于连接中的每个匹配实例 - 但是,我只需要第一个匹配。例如: 工作#,日期,发票日期,客户,批准日期,批准日期,截止日期,发货日期。

结果数据将从表A(作业)返回多行,但每个联接结果将仅返回OFA,已批准,已发货和已开票的第一个匹配项。几乎就像一个交叉表报告。

SELECT a."JobNumber" AS "Job Number", a."dateIn" AS "Date In", e."created" AS "Invoiced" , a."customer" AS "Customer", a."jobTitle" AS "Job Title", b."created" AS "OFA", c."created" AS "Approved", a."dateShip" AS "Date Due", d."created" AS "Shipped" 
FROM "@ Jobs" a
INNER JOIN "@ Statuses" b ON (a."ID"   = b."fkey" AND b."status" = 'OFA')
INNER JOIN "@ Statuses" c ON (b."fkey" = c."fkey" AND c."status" IN ('Offset Press','Indigo Press', 'Wide Format Press'))
INNER JOIN "@ Statuses" d ON (c."fkey" = d."fkey" AND d."status" IN ('Shipped', 'Partially Shipped'))
INNER JOIN "@ Statuses" e ON (d."fkey" = e."fkey" AND e."status" = 'Invoiced') 

WHERE a."currentStatus" = ? AND e."created" BETWEEN ? AND ?

ORDER BY a."JobNumber" ASC

它必须符合SQL 92.没有MSSQL,Oracle或MySQL,没有临时表,因为FileMaker不支持。

1 个答案:

答案 0 :(得分:0)

从FIleMaker 14开始,您可以使用“FETCH FIRST 1 ROWS ONLY”

SELECT a."JobNumber" AS "Job Number", a."dateIn" AS "Date In", e."created" AS "Invoiced" , a."customer" AS "Customer", a."jobTitle" AS "Job Title", b."created" AS "OFA", c."created" AS "Approved", a."dateShip" AS "Date Due", d."created" AS "Shipped" 
FROM "@ Jobs" a
INNER JOIN "@ Statuses" b ON (a."ID"   = b."fkey" AND b."status" = 'OFA')
INNER JOIN "@ Statuses" c ON (b."fkey" = c."fkey" AND c."status" IN ('Offset Press','Indigo Press', 'Wide Format Press'))
INNER JOIN "@ Statuses" d ON (c."fkey" = d."fkey" AND d."status" IN ('Shipped', 'Partially Shipped'))
INNER JOIN "@ Statuses" e ON (d."fkey" = e."fkey" AND e."status" = 'Invoiced')     
WHERE a."currentStatus" = ? AND e."created" BETWEEN ? AND ?    
ORDER BY a."JobNumber" ASC
FETCH FIRST 1 ROWS ONLY

完整规格:

http://help.filemaker.com/app/answers/detail/a_id/12061/~/specifying-offset-and-fetch-first-clauses-in-filemaker-pro-using-the-executesql