我有两张表 Invoice(
Id
,
Status
,
VendorId
,
CustomerId
,
OrderDate
,
InvoiceFor
, )
发票项(
Id
,
Status
,
InvoiceId
,
ProductId
,
PackageQty
,
PackagePrice
, )
这里 invoice.id=invoiceItem.invoiceId (Foregin key) 和 Id 字段是主键 (big int) 这些表包含 100000(invoice) 和 450000(invoiceItem) 行
现在我必须编写一个查询,它将返回发票分类帐,其中发票 = 55 或 66 并且在某个日期范围内。我还必须返回最后一个拍摄日期,其中包含该特定客户之前拍摄的产品日期。
输出应为 OrderDate、InvoiceId、CustomerId、ProductId、LastTaken、PackageQty、PackagePrice
所以我写了以下查询
SELECT a.*, (
SELECT MAX(ivv.orderdate)
FROM invoice AS ivv , invoiceItem AS iiv
WHERE ivv.id=iiv.invoiceid
AND iiv.ProductId=a.ProductId AND ivv.CustomerId=a.CustomerId AND ivv.orderDate<a.orderdate
) AS lastTaken FROM (
SELECT iv.Id, iv.OrderDate, iv.CustomerId, iv.InvoiceFor, ii.ProductId,
ii.PackageQty, ii.PackagePrice
FROM invoice AS iv, invoiceitem AS ii
WHERE iv.id=ii.InvoiceId
AND iv.InvoiceFor IN (55,66)
AND iv.Status=0 AND ii.Status=0
AND OrderDate BETWEEN '2011-01-01' AND '2011-12-31'
ORDER BY iv.orderdate, iv.Id ASC
) AS a
但我总是把时间赶出去。我将如何解决问题???
该查询的解释如下: