我目前有以下表格:
TABLE klusbonnen_deelnemers:
bonnummer (varchar) - order number
adres (varchar) - order adres
deelnemer (varchar) - user
binnen (date) - date order received
klaar (date) - original order milestone
datum_gereed (date) - date order completed
gereed (varchar) - YES or NO (YES= completed NO= Not yet completed)
datum_factuur (date) - date when user marked order completed (button clicked)
factuur (varchar) - weeknumber order completed
一个订单(bonnummer)可以有多个用户(deelnemer),他们都必须标记订单“已完成”(datum_gereed)。只有当所有用户(deelnemer)标记订单(bonnummer)“已完成”(datum_gereed)时,订单才“完成”。 我正在尝试编写一个查询,它给了我: 所有已完成的订单(bonnummer)在给定的时间跨度内(上个月)。 然而... 完成日期(datum_gereed)应保留最后日期(因为这是实际的完成日期)。 该列表应该具有最新的“标记完成”日期(datum_factuur)的订单(bonnummer)(排序DESC)(当然只有当所有用户(deelnemer)完成订单时(所有用户(deelnemers)具有gereed =“ YES“)
到目前为止我有这个:
SELECT DISTINCT tbl1.bonnummer AS 'KLUSBONNUMMER', tbl1.adres AS 'ADRES',
tbl1.binnen AS 'BINNENGEKOMEN OP', tbl1.klaar AS 'ORIGINELE STREEFDATUM',
tbl1.datum_gereed AS 'GEREEDGEKOMEN OP', tbl1.factuur AS 'WEEKNUMMER'
FROM klusbonnen_deelnemers AS tbl1
INNER JOIN
( SELECT tbl2.bonnummer
FROM klusbonnen_deelnemers AS tbl2
WHERE tbl2.bonnummer NOT IN (
SELECT tbl3.bonnummer
FROM klusbonnen_deelnemers AS tbl3
WHERE tbl3.gereed = 'NEE')
) AS tbl4 ON tbl1.bonnummer = tbl4.bonnummer
INNER JOIN
( SELECT bonnummer, MAX(datum_gereed) AS 'MAXDATUM'
FROM klusbonnen_deelnemers
GROUP BY bonnummer
) MAXFILTER ON tbl1.bonnummer = MAXFILTER.bonnummer
AND tbl1.datum_gereed = MAXFILTER.MAXDATUM
WHERE tbl1.datum_factuur BETWEEN NOW() - INTERVAL 2 MONTH AND NOW()
ORDER BY tbl1.bonnummer DESC
此查询有效,但我认为这可以通过更简单的方式完成。 最重要的是,查询仅适用于我的navicat编辑器。在我的“实时”网站上调用此查询会产生错误(WHERE子句中的子查询...)(我确实所有登录都正确,因为其他查询可以正常工作)。
有谁可以帮助(简化)此查询? THX ...
答案 0 :(得分:0)
这一部分:
INNER JOIN (SELECT tbl2.bonnummer
FROM klusbonnen_deelnemers AS tbl2
WHERE tbl2.bonnummer NOT IN
(SELECT tbl3.bonnummer
FROM klusbonnen_deelnemers AS tbl3
WHERE tbl3.gereed = 'NEE')) AS tbl4
ON tbl1.bonnummer = tbl4.bonnummer
似乎没用。尝试在“最底层” - gereed <> 'NEE'
WHERE
SELECT DISTINCT
kd.bonnummer AS 'KLUSBONNUMMER',
kd.adres AS 'ADRES',
kd.binnen AS 'BINNENGEKOMEN OP',
kd.klaar AS 'ORIGINELE STREEFDATUM',
kd.datum_gereed AS 'GEREEDGEKOMEN OP',
kd.factuur AS 'WEEKNUMMER'
FROM klusbonnen_deelnemers AS kd
INNER JOIN (
SELECT bonnummer, MAX(datum_gereed) AS 'MAXDATUM'
FROM klusbonnen_deelnemers
GROUP BY bonnummer
) AS MAXFILTER
ON (kd.bonnummer = MAXFILTER.bonnummer AND kd.datum_gereed = MAXFILTER.MAXDATUM)
WHERE
kd.gereed <> 'NEE'
kd.datum_factuur BETWEEN NOW() - INTERVAL 2 MONTH AND NOW()
ORDER BY
kd.bonnummer DESC