SQL查询问题 - 每年客户支出的总和

时间:2012-12-30 01:19:32

标签: php mysql sql

我正在尝试构建应该是(在我的脑海中)一个简单的SQL查询,以了解每个财政年度客户的发票。输出可能如下所示:

{clientName(Client A)} - {2010/2011 Value} - {2011/2012 Value} - {2012/2013 Value}

我能够实现的输出是这样的:

{clientName (Client A)} - {2010/2011 Value}
{clientName (Client A)} - {2011/2012 Value}
{clientName (Client A)} - {2012/2013 Value}
{clientName (Client B)} - {2010/2011 Value}

等等......

现在,我知道这不正确,但我正在使用的查询看起来像这样:

$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>";

如果能够对此有所了解,我将不胜感激。我已经试了好几个小时,但唉,没有运气。

谢谢, @rrfive

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

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

“技巧”是使用IF函数(或更多ANSI便携式CASE表达式)来确定行是否适用于给定的会计年度。如果是,则返回发票值,否则返回0。

将这些表达式包装在SUM聚合函数中,并在客户端上执行GROUP BY。

如果要防止返回NULL值,则可以将这些SUM表达式包装在IFNULL( ... ,0)