如果在单个查询中可以进行以下操作,我试图解决。
我们有以下查询从表A和B
获取信息SELECT
a.wj_job
,a.wj_sched
,a.wj_lump
,SUM(b.wj_billed) AS wj_billed
,SUM(b.wj_received) AS wj_recd
,a.wj_lbdate
,a.wj_fecom1
FROM ag_fsch a
JOIN ag_fschd b ON a.wj_job = b.wj_jbnum AND a.wj_sched = b.wj_sched
WHERE
a.wj_job LIKE "4733.%"
GROUP BY
a.wj_job
,a.wj_sched
ORDER BY
a.wj_job
,a.wj_sched
我想从表b中提取最后一个未付帐单日期作为上述查询的一部分。通过下面的查询可以实现相同的功能,但仅适用于原始查询中的特定结果。
SELECT
MIN(wj_bdate)
FROM ag_fschd
WHERE
wj_jbnum = 4733.00
AND wj_sched = 6
AND wj_billed <> 0
AND wj_received = 0
答案 0 :(得分:1)
我认为你可以使用条件聚合。我不确定,因为group by
中有两个键,而不仅仅是作业号。但是,这可能是您想要的输出:
SELECT a.wj_job, a.wj_sched, a.wj_lump, SUM(b.wj_billed) AS wj_billed,
SUM(b.wj_received) AS wj_recd, a.wj_lbdate, a.wj_fecom1,
MIN(CASE WHEN b.wj_sched = 6 AND b.wj_billed <> 0 AND b.wj_received = 0
THEN wj_bdate
END)
FROM ag_fsch a JOIN
ag_fschd b
ON a.wj_jbnum = b.wj_jbnum AND a.wj_sched = b.wj_sched
WHERE a.wj_jbnum LIKE '4733.%'
GROUP BY a.wj_jbnum, a.wj_sched
ORDER BY a.wj_jbnum, a.wj_sched;
答案 1 :(得分:0)
使用子查询获取每个的最小日期: -
SELECT a.wj_job,
a.wj_sched,
a.wj_lump,
SUM(b.wj_billed) AS wj_billed,
SUM(b.wj_received) AS wj_recd,
a.wj_lbdate,
a.wj_fecom1 ,
sub0.wj_bdate
FROM ag_fsch a
JOIN ag_fschd b ON a.wj_jbnum = b.wj_jbnum AND a.wj_sched = b.wj_sched
LEFT OUTER JOIN
(
SELECT wj_jbnum,
wj_sched,
MIN(wj_bdate)
FROM ag_fschd
WHERE wj_billed <> 0
AND wj_received = 0
GROUP BY wj_jbnum,
wj_sched
) sub0
ON sub0.wj_jbnum = a.wj_jbnum AND sub0.wj_sched = a.wj_sched
WHERE a.wj_jbnum LIKE "4733.%"
GROUP BY a.wj_jbnum, a.wj_sched
ORDER BY a.wj_jbnum, a.wj_sched
注意Jarlh在注释中指出,GROUP BY子句有点奇怪,因为它没有所有非聚合字段。我没有试图解决这个问题。