All pastes #207708 Raw Edit

Mine

public text v1 · immutable
#207708 ·published 2006-10-18 04:06 UTC
rendered paste body
create table invoice (
	objectid int unsigned NOT NULL,
	clientlink int unsigned NOT NULL,
	status enum('unpaid','paid') default 'unpaid',
	checkccno int unsigned default NULL,
	balance decimal(6,2) default 0,
	creationdate datetime default "0000-00-00 00:00:00",
	duedate datetime default "0000-00-00 00:00:00",
	d_sent0 datetime default "0000-00-00 00:00:00",
	d_sent1 datetime default "0000-00-00 00:00:00",
	d_sent2 datetime default "0000-00-00 00:00:00",
	d_paid datetime default "0000-00-00 00:00:00"
	/* shortnote varchar(255) */
) Engine=InnoDB;

create table invoice_items (
	invoicelink int unsigned NOT NULL,
	custpackagelink int unsigned NOT NULL,
	/* state enum('unpaid','paid') default 'unpaid', */
	amount decimal(6,2) default 0,
	danamount decimal(6,2) default 0,
	creationdate datetime default '0000-00-00 00:00:00'
) Engine=InnoDB;

create table tutos_packages (
	/* There is no objectid needed, as tutos has its own number generator */
	tutoslink int NOT NULL primary key,
	productlink int NOT NULL,
	invoicelink int unsigned NOT NULL,
	performed datetime default "0000-00-00 00:00:00",
	bugid varchar(30),
	worker char(3),
	workerid int NOT NULL,
	description varchar(120) NOT NULL,
	costperunit decimal(10,3) default 0,
	units decimal(5,3) default 0
) Engine=InnoDB;


SELECT invoice.objectid,duedate,IFNULL(sum(amount),0),IFNULL(sum(costperunit*units),0),balance FROM invoice LEFT JOIN invoice_items ON invoice_items.invoicelink=invoice.objectid LEFT JOIN tutos_packages ON tutos_packages.invoicelink=invoice.objectid WHERE clientlink = 130 GROUP BY objectid ORDER BY status DESC,duedate DESC;

If we assume there is 1 row that matches on invoice_items and 20 rows that match on tutos_packages, the sum gets messed up because the sum(amount) gets added 20 times instead of once.  How do I fix this query so it only counts sum(amount) and sum(costperunit*units) properly?

Example output:

+----------+---------------------+-------------+---------+
| objectid | duedate             | Total       | balance |
+----------+---------------------+-------------+---------+
|      133 | 2006-10-28 00:00:00 |   85.000000 |   85.00 |
|      135 | 2006-10-28 00:00:00 | 1082.500000 |  892.50 |
+----------+---------------------+-------------+---------+
2 rows in set (0.00 sec)

From this sample, Total *should* == balance but it does not where objectid=135.  133 is accurate because it only has rows on invoice_items.