如何查询SQLite在日期之间查找按ID分组的总和,最新记录?

时间:2017-07-18 12:29:21

标签: sql sqlite

Items (itemId, itemName)
Logs (logId, itemId, qtyAdded, qtyRemoved, availableStock, transactionDate)

项目的样本数据:

itemId     itemName
  1         item 1
  2         item 2

日志示例数据:

logid itemId qtyAdded qtyRemoved avlStock  transDateTime
  1      2     5405       0        5405     June 1 (4PM)
  2      2     1000       0        6405     June 2 (5PM)
  3      2        0    6000         405     June 3 (11PM)

我需要查看Items表中的所有项目及其SUM(qtyAdded),SUM(qtyRemoved),最新的availableStock(这里有一个选择transactionDate范围但默认获取所有记录的选项)。最终结果中的日期顺序无关紧要。

首选结果:(没有日期范围)

itemName  qtyAddedSum  qtyRemovedSum avlStock
 item 1      6405          6000        405
 item 2           <nothing here yet>

日期范围介于6月2日(上午8点)和6月3日(晚上11:01)之间

itemName qtyAddedSum qtyRemovedSum avlStock
 item 1      1000         6000       405
 item 2          <no transaction yet>

正如您所看到的,最终结果被分组,几乎所有我以前的查询都正确,除了我的availableStock总是错误的。如果我专注于可用的库存,我无法获得两笔款项。

2 个答案:

答案 0 :(得分:0)

您可以按总和使用组,以及

之间
 select itemName, sum(qtyAdded), sum(qtyRemoved), sum(avlStock)
 from Items
 left join Logs on logs.itemId = items.itemId
 where transDateTime between '2017-06-02 08:00:00' and '2017-06-03 23:00:00'
 group by itemId

如果你需要最后一个avlStock

   select itemName, sum(qtyAdded), sum(qtyRemoved), tt.avlStock
   from Items
   left join Logs on logs.itemId = items.itemId
   INNER JOIN (
     select logid,avlStock
    from logs
      inner join (
      select itemId, max(transDateTime) max_trans
      from Logs
      group by itemId
      )  t1 on logs.itemId = t1.ItemId and logs.transDateTime = t1.max_trans
   ) tt on tt.logId = Logs.itemId
   where transDateTime between '2017-06-02 08:00:00' and '2017-06-03 23:00:00'
   group by itemId

答案 1 :(得分:0)

好的,我尝试了这两个并且它们有效,任何人都可以确认这些是否已经有效或者是否有更有效的答案。

SELECT * FROM Items LEFT JOIN
(
    SELECT * FROM Logs LEFT JOIN
    (
          SELECT SUM(qtyAdd) AS QtyAdded, SUM(qtySub) AS QtyRemoved, availableStock AS Stock
          FROM Logs WHERE transactionDate BETWEEN julianday('2017-07-18 21:10:40')
          AND julianday('2017-07-18 21:12:00') GROUP BY itemId
    )
    ORDER BY transactionDate DESC
)
USING (itemId) GROUP BY itemName;


SELECT * FROM Items LEFT JOIN
(
    SELECT * FROM Logs LEFT JOIN
    (
          SELECT SUM(qtyAdd) AS QtyAdded, SUM(qtySub) AS QtyRemoved, availableStock AS Stock
          FROM Logs GROUP BY itemId
    )
    ORDER BY transactionDate DESC
)
USING (itemId) GROUP BY itemName;