我有这个查询来返回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);
这些访客,有些是男性,有些是女性。
我已经有一个数组,可以告诉我访问次数和相应的日期。像这样:[&#39; 2012-1-1&#39;,50]。 我的想法是有一个数组,可以保持日期,访问次数,男性人数和女性人数。像这样:[&#39; 2012-1-1&#39;,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);
EDIT2: 是的我有一个性别(int)列,男性为1,女性为2
答案 0 :(得分: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";
如果您要格式化性别而不是数字,则希望将其显示为male
或female
$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
攻击,请阅读以下文章
答案 1 :(得分: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";
答案 2 :(得分: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;