[英]SQL Query Issues - Sum of client spend per year
I'm trying to build what should be (in my mind anyway) a simply SQL query to understand what clients have been invoiced each financial year. 我正在尝试构建一个(无论如何在我看来)简单的SQL查询,以了解每个财政年度向哪些客户开具发票。 The output might look like this: 输出可能如下所示:
{clientName (Client A)} - {2010/2011 Value} - {2011/2012 Value} - {2012/2013 Value} {clientName(客户A)}-{2010/2011价值}-{2011/2012价值}-{2012/2013价值}
What I've been able to achieve is an output that looks like this: 我已经能够实现的输出如下所示:
{clientName (Client A)} - {2010/2011 Value}
{clientName (Client A)} - {2011/2012 Value}
{clientName (Client A)} - {2012/2013 Value}
{clientName (Client B)} - {2010/2011 Value}
And so on… 等等…
Now, I know this is not correct but the query I'm working with looks like this: 现在,我知道这是不正确的,但是我正在使用的查询如下所示:
$query = "SELECT i.invoiceValue, fy.year, c.clientName, c.clientID FROM cms_invoices i
LEFT JOIN cms_financialYear fy ON fy.yearID = i.yearID
LEFT JOIN cms_projects p ON p.projectID = i.projectID
LEFT JOIN cms_clients c ON c.clientID = p.clientID
ORDER BY fy.year, c.clientName";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['year'] . " - ";
echo $row['clientName'] . " - $";
echo number_format($row[invoiceValue], 2, '.', ',') . "";
echo "<br>";
I'd be much appreciated if I could get some sort of a steer on this. 如果能对此有所帮助,我将不胜感激。 I've tried for hours but alas, no luck. 我已经尝试了几个小时,但可惜没有运气。
Thanks, @rrfive 谢谢@rrfive
You could try something like this: 您可以尝试这样的事情:
SELECT c.clientID
, c.clientName
, SUM(IF(fy.year=2010,i.invoiceValue,0)) AS fy_2010
, SUM(IF(fy.year=2011,i.invoiceValue,0)) AS fy_2011
, SUM(IF(fy.year=2012,i.invoiceValue,0)) AS fy_2012
FROM cms_invoices i
LEFT
JOIN cms_financialYear fy ON fy.yearID = i.yearID
LEFT
JOIN cms_projects p ON p.projectID = i.projectID
LEFT
JOIN cms_clients c ON c.clientID = p.clientID
GROUP BY c.clientID, c.clientName
ORDER BY c.clientID, c.clientName
The "trick" is to use an IF
function (or a more ANSI portable CASE expression), to determine if a row applies to a given fiscal year. “技巧”是使用IF
函数(或更具ANSI可移植性的CASE表达式)来确定行是否适用于给定的会计年度。 If it does, then return the invoice value, otherwise, return a 0. 如果是,则返回发票值,否则,返回0。
Wrap those expressions in a SUM aggregate function, and do the GROUP BY on the client. 将这些表达式包装在SUM聚合函数中,然后在客户端上执行GROUP BY。
If you want to guard against returning a NULL value, then you can wrap those SUM expressions in an IFNULL( ... ,0)
如果要防止返回NULL值,则可以将这些SUM表达式包装在IFNULL( ... ,0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.