2012-11-20 61 views
1

我有此查詢返回2個日期之間的訪問者數量。查詢返回基於性別的訪問者數量

$SQLVisit = "SELECT  
      count(score) as counts, 
      date FROM persons 
      WHERE date > '".$_SESSION['data1']."' AND date < '".$_SESSION['data2]."' 
      GROUP BY date 
      ORDER BY date asc"; 

$result = mysql_query($SQLVisit); 
$num = mysql_num_rows($result); 

這些訪問者,有些是男性和其他女性。

我已經有一個數組,使我的訪問次數和相應的日期。像這樣:['2012-1-1',50]。 我的想法是有一個數組,可以保存日期,訪問次數,男性人數和女性人數。像這樣:['2012-1-1',50,35.15]。

有什麼想法? ps:使用PHP的Im。

編輯:數組代碼

$data[0] = array('day','counts');  
    for ($i=1; $i<($num+1); $i++) 
    { 
     $data[$i] = array(substr(mysql_result($result, $i-1, "date"), 0, 20), 
      (int) mysql_result($result, $i-1, "counts"),); 
    } 
    echo json_encode($data); 

EDIT2: 是的,我有一個性別(INT)柱,1男2女

+0

你有你的表中的性別欄? –

+0

性別存儲在哪裏?數據庫中是否有額外的字段? – Jens

+0

是的,我有一個性別(int)列,男性爲1,女性爲2 – pleaseDeleteMe

回答

1

如果你有gender列,儘量

$SQLVisit = "SELECT date, gender, 
        count(score) as counts, 
      FROM persons 
      WHERE date > '".$_SESSION['data1']."' AND date < '".$_SESSION['data2]."' 
      GROUP BY date, gender 
      ORDER BY date asc"; 

如果要格式化性別而不是數字,則要將其顯示爲malefemale

$SQLVisit = "SELECT date, 
        IF(gender = 1, 'Male', 'Female') gender, 
        count(score) as counts, 
      FROM persons 
      WHERE date > '".$_SESSION['data1']."' AND date < '".$_SESSION['data2]."' 
      GROUP BY date, gender 
      ORDER BY date asc"; 

,如果你也也想擁有這樣的格式,

date Male  Female 
=========================== 
'date'  5   6 

使用以下查詢

SELECT DATE, 
     SUM(CASE WHEN gender = 1 then 1 ELSE 0 END) Male, 
     SUM(CASE WHEN gender = 2 then 1 ELSE 0 END) Female 
FROM person 
-- WHERE clause 
GROUP BY DATE 
-- ORDER clause 

查詢與SQL Injection脆弱的,請閱讀以下

文章
+0

是的,我有一個性別(int)列,只有兩個數據:男性1個,女性2個。這沒有工作,因爲我需要解決數組 – pleaseDeleteMe

+0

感謝您的建議 – pleaseDeleteMe

+0

@skdnewbie看到我的更新回答:D –

1

您可以使用SUM(IF()):

$SQLVisit = "SELECT  
      count(score) as counts, 
      SUM(IF(gender=1,1,0)) as male, 
      SUM(IF(gender=2,1,0)) as female, 
      date FROM persons 
      WHERE date > '".$_SESSION['data1']."' AND date < '".$_SESSION['data2]."' 
      GROUP BY date 
      ORDER BY date asc"; 
+0

什麼意思(性別= 1,1,0)和(性別= 2,1,0)? – pleaseDeleteMe

+0

@skdnewbie這只是一個簡短的陳述。如果性別爲1,則TRUE(1)否則爲FALSE(0)。 – wesside

+0

IF是重要的;)如果性別爲1 else,則IF(gender = 1,1,0)返回1.這是針對每行計算的,並使用SUM進行求和。 – Jens

0

你可以這樣做:

SELECT  
    SUM(CASE WHEN Gender = 1 THEN 1 ELSE 0) malescounts, 
    SUM(CASE WHEN Gender = 2 THEN 1 ELSE 0) femalescounts, 
    count(score) as counts 
FROM persons 
WHERE date > ... 
GROUP BY date;