1

我有这个查询来返回两个日期之间的访问者数量。

$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。

编辑:数组代码

$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);

编辑2:是的,我有一个性别(int)列,男性为 1,女性为 2

4

3 回答 3

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,请阅读下面的文章

于 2012-11-20T14:12:18.650 回答
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"; 
于 2012-11-20T14:12:55.863 回答
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;
于 2012-11-20T14:16:37.473 回答