2017-04-15 26 views
2

所以我有具有以下結構MySQL的 - 計算一個數據類型的出現的唯一的號碼在給定日期

CREATE TABLE `offer_order` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 
`order_id` bigint(20) unsigned NOT NULL, 
`offer_id` bigint(20) unsigned NOT NULL, 
`created_at` datetime NOT NULL, 
`updated_at` datetime NOT NULL, 
PRIMARY KEY (`id`), 
KEY `order_id` (`order_id`,`offer_id`)); 

以下爲offer_order

id | order_id | offer_id | created_at 
--------------------------------------------- 
1 | 1  | 1  | 2017-04-16 00:00:00 
2 | 2  | 1  | 2017-04-16 00:00:00 
3 | 1  | 2  | 2017-04-16 00:00:00 
4 | 3  | 3  | 2017-04-17 00:00:00 
5 | 3  | 1  | 2017-04-18 00:00:00 
6 | 2  | 1  | 2017-04-18 00:00:00 
一些樣本數據1的數據透視表

現在的數據出來,我想上面的樣本數據是

offer_redemption_date | no_of_unique_orders_that_day 
---------------------------------------------------- 
2017-04-16   | 2 
2017-04-17   | 1 
2017-04-18   | 2 

我嘗試以下查詢來獲取一個階段:

select date(created_at) as offer_redemption_date, order_id, count(order_id) as count from offer_order group by offer_redemption_date, order_id; 

這給了我下面的結果

offer_redemption_date|order_id|count 
------------------------------------- 
2017-04-16   | 1  | 2 
2017-04-16   | 2  | 1 
2017-04-17   | 3  | 1 
2017-04-18   | 2  | 1 
2017-04-18   | 3  | 1 

現在什麼我不能做的是依靠某一特定日期的ORDER_ID出現的唯一編號。提前致謝。 :)

回答

3

您可以使用DISTINCT爲:

SELECT DATE(created_at) AS offer_redemption_date, 
     COUNT(DISTINCT(order_id)) AS count 
FROM offer_order 
GROUP BY offer_redemption_date;

所以在這裏你COUNTDISTINCT值的order_id數量。

+1

只要我寫的問題,我回憶起這段查詢。作爲選擇日日期(created_at),由過時計數(不同(ORDER_ID))作爲從unique_orders組offer_order。謝謝 :) – 1ns4n3

1

和不同的做法:

select created_at as offer_redemption_date, count(*) as no_of_unique_orders_that_day 
from (
select count(*) cnt, order_id, created_at 
from `offer_order` 
group by order_id, created_at 
) x 
group by created_at 

派生表的做法並不像COUNT DISTINCT解決方案優雅,但它可以在其他情況下,在這樣的快捷方式並不存在很大的幫助。

相關問題