我有一张包含以下数据的表格:
______________________
| Name | Date |
----------------------
| Bob | 2016-09-16 |
| Ben | 2016-10-03 |
| Sam | 2016-10-03 |
使用以下内容:
SELECT
case
when datediff( CURDATE(), `the_date`) = 3 then '3 Days'
when datediff( CURDATE(), `the_date`) between 4 and 6 then '4-6 Days'
when datediff( CURDATE(), `the_date`) > 6 then '7 or more days'
end as days,
sum( case
when datediff( CURDATE(), `the_date`) <= 3 then 1
when datediff( CURDATE(), `the_date`) between 4 and 6 then 1
when datediff( CURDATE(), `the_date`) > 6 then 1
else 0
end ) as tot
FROM my_table
GROUP BY
case
when datediff( CURDATE(), `the_date`) <= 3 then '3 Days'
when datediff( CURDATE(), `the_date`) between 4 and 6 then '4-6 Days'
when datediff( CURDATE(),`the_date`) > 6 then '7 or more days'
end ;
然后使用
echo '<p>'.$row['tot'].'</p>';
我得到以下结果,将行排序为行是否少于3天,4到6天或超过7天。
1
2
理想情况下,我想将一个类应用于p标签,例如class =&#34; urgent&#34;对于7天以上的橙色,4至6天的橙色,然后绿色长达3天。然后,我想用#34等唯一文字包装数字;您迫切需要回复结果应用程序&#34;
答案 0 :(得分:2)
我测试您要查找的值的数据结果,并根据值有条件地指定一个类名。
if ($row['days'] == '7 or more days') {
$css_class = 'urgent';
} else {
$css_class = 'normal';
}
printf("<p class='%s'>%s</p>", $css_class, $row['tot']);
我不建议在查询中硬编码您的css类名。不要将数据库查询与表示层混合在一起,这只会在代码中造成混淆和不恰当的耦合。
答案 1 :(得分:0)
您可以在查询中添加一列(my_class),并将结果添加到您的p标记
中SELECT
case
when datediff( CURDATE(), `the_date`) = 3 then '3 Days'
when datediff( CURDATE(), `the_date`) between 4 and 6 then '4-6 Days'
when datediff( CURDATE(), `the_date`) > 6 then '7 or more days'
end as days,
sum( case
when datediff( CURDATE(), `the_date`) <= 3 then 1
when datediff( CURDATE(), `the_date`) between 4 and 6 then 1
when datediff( CURDATE(), `the_date`) > 6 then 1
else 0
end ) as tot ,
case
when datediff( CURDATE(), `the_date`) = 3 then 'green'
when datediff( CURDATE(), `the_date`) between 4 and 6 then 'orange'
when datediff( CURDATE(), `the_date`) > 6 then 'red'
end as my_class
FROM my_table
GROUP BY
case
when datediff( CURDATE(), `the_date`) <= 3 then '3 Days'
when datediff( CURDATE(), `the_date`) between 4 and 6 then '4-6 Days'
when datediff( CURDATE(),`the_date`) > 6 then '7 or more days'
end ;
echo '<p class="'. $row['my_class'] . '" >'.$row['tot'].'</p>'; your query with the proper class a