2014-12-11 394 views
0

我想統計訪問者數鼻子。 這裏是MySQL Count Noses

UID | VisitDate | VisitTime 
----------------------------- 
11 | 2014-12-11 | 10:18 
12 | 2014-12-11 | 11:42 
13 | 2014-12-11 | 12:15 
11 | 2014-12-11 | 13:31 
14 | 2014-12-12 | 07:19 
12 | 2014-12-13 | 09:18 
12 | 2014-12-13 | 16:55 

我已經解決了使用下面的SQL計數參觀者表:

SELECT COUNT(*) AS visitors FROM record WHERE VisitDate >= '2014-12-11' AND VisitDate <= '2014-12-13' 

,並導致這裏:

visitors 
--------- 
7 

但我解決不了的計數鼻子。 如果一位訪客在同一天來過兩次或兩次以上,應該只計算一次。

從上表中可以看出,UID 11在2014-12-11兩次出現,UID 12在2014-12-13兩次出現,所以只計算一次。無論如何:我可以得到5的結果。

+0

首先,修改您的模式,使日期和時間在同一列。 – Strawberry 2014-12-11 05:38:15

回答

-1

編輯我更新了查詢,並添加SQL小提琴降價。

您必須先按訪問日期進行分組,每個訪問者每天的訪問次數會縮短一次。接下來,你要計算訪客人數。

SQL Fiddle

MySQL的32年5月5日架構設置

create table record(
    UID int, 
    VisitDate date, 
    VisitTime time 
); 


insert into record(UID, VisitDate, VisitTime) 
select 11 , '2014-12-11', '10:18'; 

insert into record(UID, VisitDate, VisitTime) 
select 12 , '2014-12-11', '11:42'; 

insert into record(UID, VisitDate, VisitTime) 
select 13 , '2014-12-11', '12:15'; 

insert into record(UID, VisitDate, VisitTime) 
select 11 , '2014-12-11', '13:31'; 

insert into record(UID, VisitDate, VisitTime) 
select 14 ,'2014-12-12', '07:19'; 

insert into record(UID, VisitDate, VisitTime) 
select 12 ,'2014-12-13', '09:18'; 

insert into record(UID, VisitDate, VisitTime) 
select 12 , '2014-12-13', '16:55'; 

查詢1

 select count(UID) as noses 
    from (
     SELECT UID, VisitDate 
      FROM record 
      WHERE VisitDate >= '2014-12-11' AND VisitDate <= '2014-12-13' 
      Group by uid, VisitDate 
    ) visitors 

Results

| NOSES | 
|-------| 
|  5 | 
+0

在結果中得到了2,1,2,1,1。與上面的查詢相同,但分割成每個UID。 – AkiEru 2014-12-11 05:04:34

+0

嘿,它的工作! – AkiEru 2014-12-11 05:33:04

0
SELECT COUNT (DISTINCT UID) visitors FROM record WHERE VisitDate BETWEEN '2014-12-11' AND '2014-12-13' GROUP BY (DATE); 
+0

得到4結果。 – AkiEru 2014-12-11 04:48:45

0

使用HAVING CLUASE

SELECT COUNT(*) AS visitors FROM record having VisitDate >= '2014-12-11' AND VisitDate <= '2014-12-13'and COUNT(*)=1 
+0

你有一個語法錯誤。 您的意思是:SELECT COUNT(*)AS visitor FROM record WHERE visitdate BETWEEN'2014-12-11'和'2014-12-13'HAVING COUNT(*)= 1? 但它返回零行。 – AkiEru 2014-12-11 04:46:54

+0

這是我的錯誤,我更新它... – Dhaval 2014-12-11 04:47:38

0
DROP TABLE IF EXISTS record; 

create table record 
    (UID int not null 
    , VisitDate datetime not null 
    , PRIMARY KEY(UID,VisitDate) 
    ); 


insert into record(UID, VisitDate) VALUES 
(11 , '2014-12-11 10:18:00'), 
(12 , '2014-12-11 11:42:00'), 
(13 , '2014-12-11 12:15:00'), 
(11 , '2014-12-11 13:31:00'), 
(14 , '2014-12-12 07:19:00'), 
(12 , '2014-12-13 09:18:00'), 
(12 , '2014-12-13 16:55:00'); 

SELECT SUM(total) grand_total 
    FROM 
     (SELECT COUNT(DISTINCT uid) total 
      FROM record 
     WHERE visitdate BETWEEN '2014-12-11 00:00:00' AND '2014-12-12 23:59:00' 
     GROUP 
      BY visitdate 
    ) x;