查找将来某个时间具有相应记录的记录

时间:2018-01-26 20:04:31

标签: mysql sql memsql

我有记录表(目前是一个列存储),它具有以下布局:

id  | person_id | practice_key | order_date
-------------------------------------------
1   | 001       | prac-A       | 1501098844
2   | 001       | prac-A       | 1516996444
...

idperson_id是UUID(存储为CHAR),practice_keyVARCHARorder_date是纪元秒存储为NUMERIC

我想仅选择person_id以后至少有六个月order_date的人。

我尝试过以下方法:

SELECT MIN(DATE(FROM_UNIXTIME(order_date))) min_order_date, person_id 
FROM the_table WHERE 
DATE(FROM_UNIXTIME(order_date)) >= 
DATE_ADD(MIN(DATE(FROM_UNIXTIME(order_date))), INTERVAL 6 MONTH);

SELECT MIN(DATE(FROM_UNIXTIME(order_date))) min_order_date, person_id 
FROM the_table WHERE 
DATE(FROM_UNIXTIME(order_date)) >= 
DATE_ADD(MIN(DATE(FROM_UNIXTIME(order_date))), INTERVAL 6 MONTH)
GROUP BY person_id;

但是我收到以下错误:[HY000][1111] Invalid use of group function

我正在使用MemSQL v6.0

2 个答案:

答案 0 :(得分:1)

在澄清他的立场后,我会尝试以下方法。它只是加入到表中,并抓取用户的第一个/最后一个订单。 (您应该直接从persons表格加入订单,以避免重复,以及底部的其他GROUP_BY语句。(已加入sqlfiddle显示此信息作品):

SELECT
  orders.person_id,
  first_order.order_date AS min_order_date,
  last_order.order_date AS max_order_date
FROM `orders`
LEFT JOIN `orders` first_order ON (
    first_order.person_id = orders.person_id 
    AND first_order.order_date = (
        SELECT MIN(order_date)
        FROM `orders`
        WHERE person_id = orders.person_id
    )
)
LEFT JOIN `orders` last_order ON (
    last_order.person_id = orders.person_id 
    AND last_order.order_date = (
        SELECT MAX(order_date)
        FROM `orders`
        WHERE person_id = orders.person_id
    )
)
WHERE FROM_UNIXTIME(last_order.order_date) >= DATE_ADD(FROM_UNIXTIME(first_order.order_date), INTERVAL 6 MONTH)
GROUP BY person_id

答案 1 :(得分:1)

SELECT DATE(MIN(FROM_UNIXTIME(t2.order_date))), t1.person_id 
FROM the_table t1
INNER JOIN the_table t2 ON t1.person_id=t2.person_id
AND DATE(FROM_UNIXTIME(t1.order_date)) >= DATE_ADD(DATE(FROM_UNIXTIME(t2.order_date)), INTERVAL 6 MONTH)
GROUP BY t1.person_id;