我还在学习PHP作为初学者,我的公司已经责成我创建一个程序来按班次计算每日销售额。
我有两张桌子:
attendance
id
date
time
brand
branch
shift
attendanceout
id
date
time
brand
branch
sales
因此,当员工进来时,他们会把参加者放在考勤桌上,当他们外出时,他们的参赛作品会以当天的销售情况参加。
我想要的是,数据是这样的:
Date Shift Total Sales
10/02/2014 Morning 2000
10/02/2014 Closing 1000
11/02/2014 Morning 3000
11/02/2014 Closing 1500
我希望我能够解释它。
这就是我目前的情况:
SELECT a.date,
SUM(IF(b.shift = 'Morning' AND b.date=a.date AND a.branch='DCC' AND a.brand='NISA', a.sales, 0)) AS 'Morning',
CASE WHEN b.shift = 'Mid' AND b.date=a.date AND a.branch='DCC' AND a.brand='NISA' THEN sum(a.sales) ELSE 0 END AS Mid,
CASE WHEN b.shift = 'Closing' THEN sum(a.sales) ELSE 0 END AS Closing,
sum(a.sales) AS Total
FROM attendanceout a, attendance b
WHERE a.date>='$fromdate' AND a.date<='$todate'
GROUP BY a.date
我也想知道如何在php中显示它。
答案 0 :(得分:0)
如果我正确地阅读了您的问题,您有两个'shift'值,即Morning
和Closing
。
目前尚不清楚如何明确地加入这两个表格。我猜它在id
和date
上。我想两个表中的time
列不匹配。
如果员工在午夜过夜怎么办?
我认为你可以比你所展示的更简单地处理这个问题。
SELECT a.date, b.shift, SUM(b.sales) as total_sales
FROM attendance AS a
JOIN attendanceout AS b ON a.id=b.id AND a.date=b.date
WHERE a.branch = 'DCC'
AND a.brand = 'NISA'
AND a.date >= :startdate
AND a.date <= :enddate
GROUP BY a.date, b.shift DESC WITH ROLLUP
WITH ROLLUP
会在每个date
和shift
行之后为您提供汇总行,其中包含一整天的销售额。
然后,您可以将每一天的行(早上,结束,汇总)转移到显示程序中的列。
我使用ORDER BY ... shift DESC
作为黑客攻击,因为我们希望Morning
移位在Closing
移位之前。
这是PHP部分......
$db = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'username', 'password');
$query = "paste it in from up there^";
$stmt = $db->prepare($query);
$stmt->execute(array(":startdate" => $start, ":enddate:" => $end));
$stmt->bindColumn(1, $date);
$stmt->bindColumn(2, $shift);
$stmt->bindColumn(3, $sales);
echo "<table>";
echo "<th><td>Date</td><td>Morning</td><td>Closing</td><td>Total</td></th>\n";
$olddate = "";
while ($stmt->fetch(PDO::FETCH_BOUND)) {
if (isset ($date)) { /* skip NULL date (at end of rollup) */
if ($olddate != $date) {
/* new date, new row */
if ($olddate != "") {
/* if we had a previous date row, end it */
echo "</tr>\n";
}
/* start a new row */
echo "<tr><td>$date</td>";
$olddate = $date;
}
/* write the sales value to the table */
echo "<td>$sales</td>";
}
if ($olddate != "") {
/* we had a previous date row, end it */
echo "</tr>\n";
}
}
echo "<table>\n";
如果特定日期完全错过特定班次,这将无法正常工作;它假设SQL结果集中的每一天都由三行表示,每行一个。但它应该让你开始。