MySQL根据两个时间戳列获取结果集

时间:2014-10-20 09:21:11

标签: php mysql

希望有人可以帮助我解决这个问题,真的是盯着自己。

我有一个存储用户已选择的产品的表格,在该表格中我存储了ordertime和pickup以及picktime。所以structur是索引(PRIMARY INT),ordernr(INT),ordertime(TIMESTAMP),productid(INT),pickup(TINYINT),pickupuptime(TIMESTAMP)。

现在我想得到一个图表的结果集,即日期,订购产品的数量以及按日期分组和按顺序排序的产品数量。我现在的问题是我得到了几乎正确的数字,但是拾取的数字被计入有序数字中,我似乎无法理解这一点。

SELECT (case when pickedup = '1' then DATE(order_detail.pickeduptime) else DATE(order_detail.ordertime) end) AS x,COUNT(productid) AS y,SUM(case when pickedup = '1' then 1 else 0 end) AS z FROM order_detail WHERE productid = '127' AND YEAR(`ordertime`) = YEAR(NOW()) GROUP BY x ORDER BY x asc

任何帮助都会受到很多关注。 : - )

更新:

1   index   int(11)         AUTO_INCREMENT  Primary
2   ordernr int(11)         
3   productid   int(11)     
4   price   int(11)     
5   ordertime   timestamp   CURRENT_TIMESTAMP
6   pickedup    tinyint(4)  0
7   pickeduptime    timestamp   0000-00-00 00:00:00

表格看起来如何。

2 个答案:

答案 0 :(得分:0)

不确定你的问题究竟是什么,但我认为你有一个语法错误:忘了在“结束”之后放一个“CASE”,如MySQL Reference

答案 1 :(得分:0)

可能有用的第一件事是正确格式化SQL:

SELECT 
  (CASE 
     WHEN pickedup = '1' THEN DATE(pickeduptime) 
     ELSE DATE(ordertime) 
   END) AS x,
  COUNT(productid) AS y,
  SUM(CASE 
        WHEN pickedup = '1' THEN 1 
        ELSE 0 
      END) AS z 
FROM 
  order_detail 
WHERE 
  productid = '127' AND 
  YEAR(ordertime) = YEAR(NOW()) 
GROUP BY x 
ORDER BY x ASC

现在我需要找出你想要做的事情。这是真正的问题开始的地方。目前还不清楚您是否重复使用表中的行来进行拾取。对不起,我帮不了你。你的SQL非常奇怪。对于像这样简单的事情,您不需要使用两个CASE命令。

我也无法理解你的SQL,按两列的日期分组?

仔细阅读后,我想我开始明白你想要什么了。您想查看每个日期订购和提取的产品数量。我不会尝试使用一个SQL命令,而是使用两个。两行,两个SQL命令。 : - )

首先是一个简单的产品:按日期订购,分组和排序的产品数量:

SELECT 
  DATE(ordertime) as orderdate,
  COUNT(productid) AS quantity
FROM 
  order_detail 
WHERE 
  productid = '127' AND 
  YEAR(ordertime) = YEAR(NOW()) 
GROUP BY orderdate 
ORDER BY orderdate ASC

现在订购的产品尚未上市:

SELECT 
  DATE(ordertime) as orderdate,
  COUNT(productid) AS quantity
FROM 
  order_detail 
WHERE 
  productid = '127' AND 
  YEAR(ordertime) = YEAR(NOW()) AND
  pickedup != '1'
GROUP BY orderdate 
ORDER BY orderdate ASC

现在已经提货的产品仍按订单日期排序:

SELECT 
  DATE(ordertime) as orderdate,
  COUNT(productid) AS quantity
FROM 
  order_detail 
WHERE 
  productid = '127' AND 
  YEAR(ordertime) = YEAR(NOW()) AND
  pickedup = '1'
GROUP BY orderdate 
ORDER BY orderdate ASC

这里的发货日期相同:

SELECT 
  DATE(pickeduptime) as pickedupdate,
  COUNT(productid) AS quantity
FROM 
  order_detail 
WHERE 
  productid = '127' AND 
  YEAR(ordertime) = YEAR(NOW()) AND
  pickedup = '1'
GROUP BY pickedupdate
ORDER BY pickedupdate ASC

现在,您可以使用其中任何一个在图表中绘制一条线。

如果你坚持一个查询,你可以使用这个:

SELECT 
  DATE(ordertime) as orderdate,
  SUM(pickedup) AS pickedup_quantity,
  SUM(1-pickedup) AS not_pickedup_quantity
FROM 
  order_detail 
WHERE 
  productid = '127' AND 
  YEAR(ordertime) = YEAR(NOW())  
GROUP BY orderdate 
ORDER BY orderdate ASC

请注意,所有内容都必须按一个日期排序。