我有这样的表结构。
+--------------------------+------------------------+
| id | date | property_id | - other cols - |
+--------------------------+------------------------+
| 1 | 2012-12-04 | 102 |
| 2 | 2012-12-05 | 101 |
| 3 | 2012-12-05 | 102 |
| 4 | 2012-12-05 | 103 |
| 5 | 2012-11-07 | 101 |
| 6 | 2012-11-07 | 102 |
| 7 | 2012-11-07 | 103 |
| 8 | 2012-10-08 | 101 |
| 9 | 2012-10-08 | 102 |
| 10 | 2012-10-08 | 103 |
| 11 | 2012-10-08 | 104 |
+-----+--------------+-------------+-----------------+
这是一张跟踪房产价格和其他历史数据的历史表。 id
是唯一ID,property_id
随着时间的推移有多个条目。每周进行历史数据的批量输入。例如,对于两个不同的日期,我们具有相同的属性ID,表示两个日期的价格变化。
现在我需要的是找到特定的给定时间段(日期之间)。
我希望我的解释足够清楚。
将前一周的#2更改为上一个输入日期。
答案 0 :(得分:1)
对于第一个问题,您可以使用以下查询:
Select count(distinct(property_id)) from table-name
where date Between start_date AND end_date
AND
property_id != ALL
(
Select distinct(property_id)
from table-name
where date < start_date
)
这将在start_date日期之后显示所有新属性_d,直到end_date
对于第二个,你可以使用它:
Select count(distinct(property_id)) from table-name
where date < start_date
AND
property_id != ALL
(
Select distinct(property_id)
from table-name
where date Between start_date AND end_date
)
这将显示start_date之前的所有property_id,它们在start_date和end_date中不存在
答案 1 :(得分:1)
假设,表名为orders
SELECT
SUM(total.property_id_count) as total_property
FROM
(
SELECT
count(all_order.property_id) as property_id_count,
date_order.property_id from orders as all_order
RIGHT JOIN
(SELECT orders.* FROM orders WHERE `date` BETWEEN $start_date AND $end_date) as date_order
ON all_order.id = date_order.id
GROUP BY all_order.property_id
HAVING COUNT(all_order.property_id) > 1) AS total
SELECT
SUM(total.property_id_count) as total_property
FROM
(
SELECT date_order.date,
count(all_order.property_id) as property_id_count,
date_order.property_id from orders as all_order
RIGHT JOIN
(
SELECT orders.* FROM orders
where date between date_sub(now(),INTERVAL 1 WEEK) and now()
) as date_order
ON all_order.id = date_order.id
GROUP BY all_order.property_id
HAVING COUNT(all_order.property_id) > 1
) as total