我正在尝试按以下格式提取显示最近两个完整日历月销售额的报告:
Customer August 2013 September 2014
Company A 1,250 2,543
Company B 4,245 1,423
Company C 1,432 1,642
我有一张表,其中包含客户和个人交易以及成本。我很好,但不知道如何让两列彼此相邻。
select customers.customer as Customer,
sum(job.price) as August_2014
from job,customers
where customers.cust_id=job.customer
and
job.collect_date between '2014-08-01' and '2014-08-31'
group by customer
order by August_2014 desc
limit 0,10
感谢您的帮助。
约翰
答案 0 :(得分:1)
在SUM()函数中使用case表达式,如下所示:
SELECT
customers.customer AS Customer
, SUM(case when job.collect_date >= '2014-08-01' and job.collect_date < '2014-09-01' THEN job.price ELSE 0 END) AS August_2014
, SUM(case when job.collect_date >= '2014-09-01' and job.collect_date < '2014-10-01' THEN job.price ELSE 0 END) AS September_2014
FROM job
INNER JOIN customers ON customers.cust_id = job.customer
WHERE ( job.collect_date >= '2014-08-01' AND job.collect_date < '2014-10-01' )
GROUP BY
customers.customer
ORDER BY
August_2014 DESC
limit 0,10
;
我更改了连接语法,强烈建议使用这样的显式连接。
另请注意,我已更改&#34;日期范围&#34;的方法。只是不要相信&#34;之间&#34;为了这。始终使用上面显示的方法,数据中不会有任何间隙或重叠(即您的数字将是准确的)。
(date_field&gt; = lower_date_here AND date_field&lt; higher_date_here)
正如您所看到的,&#34;更高的日期&#34;比原来的还要早一天,因为我们在较高的日期使用的比较少
答案 1 :(得分:0)
试试这个:
SELECT
customers.customer AS Customer,
MONTH(job.collect_date) AS Month,
sum(job.price) AS SumPrice
FROM
job,
customers
WHERE
customers.cust_id = job.customer
GROUP BY
customer,
MONTH(job.collect_date)
您不能再以order by
价格执行。我相信你可以自己制作桌子吗?
不,人们不能自己编写PHP,并想要一个例子:
// the sql command
$sql = "SELECT
customers.customer AS Customer,
MONTH(job.collect_date) AS Month,
sum(job.price) AS SumPrice
FROM
job,
customers
WHERE
customers.cust_id = job.customer
GROUP BY
customer,
MONTH(job.collect_date)";
// fetching data
if ($result = $mysqli->query($sql))
{
while($row = $result->fetch_assoc())
{
extract($row);
$data[$Customer][$Month] = $SumPrice;
}
$result->close();
}
// render
foreach($data as $customer => $prices)
{
echo $customer;
foreach($prices as $month => $price)
{
echo ' '.$price;
}
echo '<br>';
}
请注意,表格渲染是非常基本的,但它给了你这个想法,你需要对它进行一些工作以使其更好。无论数据库中的哪个月,这都可以使用。主要优点是SQL查询的简单性。