我有记录表(目前是一个列存储),它具有以下布局:
id | person_id | practice_key | order_date
-------------------------------------------
1 | 001 | prac-A | 1501098844
2 | 001 | prac-A | 1516996444
...
id
,person_id
是UUID(存储为CHAR
),practice_key
是VARCHAR
,order_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
答案 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;