表结构法案
CREATE TABLE IF NOT EXISTS `bill` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`agent_id` int(11) NOT NULL,
`date` date NOT NULL,
`amount` int(100) NOT NULL,
`cheque` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;
--
-- Dumping data for table `bill`
--
INSERT INTO `bill` (`id`, `agent_id`, `date`, `amount`, `cheque`) VALUES
(1, 1, '2013-01-01', 10, 15),
(2, 1, '2013-01-01', 10, 0),
(3, 2, '2013-01-02', 10, 0),
(4, 1, '2013-01-03', 12, 0),
(5, 3, '2013-01-04', 100, 0),
(6, 2, '2013-01-05', 14, 0),
(7, 5, '2013-01-05', 18, 0),
(8, 7, '2013-01-05', 22, 0),
(9, 6, '2013-01-04', 19, 0),
(10, 6, '2013-01-06', 20, 0),
(11, 5, '2013-01-07', 21, 0),
(12, 6, '2013-01-08', 11, 0),
(13, 7, '2013-02-09', 19, 0),
(14, 6, '2013-01-10', 150, 0),
(15, 1, '2012-12-31', 100, 0),
(16, 1, '2012-01-11', 500, 20),
(17, 1, '2013-02-01', 210, 0),
(18, 1, '2013-02-18', 100, 0),
(19, 6, '2013-01-31', 100, 0),
(20, 3, '2013-01-11', 250, 50);
表结构 bill_agents
CREATE TABLE IF NOT EXISTS `bill_agents` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(11) NOT NULL,
`target` int(11) NOT NULL,
`join_date` date NOT NULL,
`resign_date` date NOT NULL,
`hide` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
--
-- Dumping data for table `bill_agents`
--
INSERT INTO `bill_agents` (`id`, `name`, `target`, `join_date`, `resign_date`, `hide`) VALUES
(1, 'Agent 1', 10, '2013-01-01', '0000-00-00', 0),
(2, 'Agent 2', 5000, '2013-01-01', '0000-00-00', 0),
(3, 'Agent 3', 5000, '2013-01-01', '0000-00-00', 0),
(4, 'Agent 4', 5000, '2013-01-03', '2013-01-06', 0),
(5, 'Agent 5', 5000, '2013-01-01', '0000-00-00', 0),
(6, 'Agent 6', 5000, '2013-01-02', '0000-00-00', 0),
(7, 'Agent 7', 5000, '2013-01-02', '0000-00-00', 1);
( 1-31 是日期)具有以下代码
<table width="100%" border="1" cellspacing="4" cellpadding="1">
<tr>
<td> </td>
<?php
for ($i=01; $i<=31; $i++)
{?>
<td><?php echo $i; ?></td>
<?php
}
?>
<td>Total</td>
</tr>
<?php
$query4 = "SELECT DISTINCT bill.agent_id, bill.date, SUM(bill.amount + bill.cheque) AS total, bill_agents.id,bill_agents.name ".
"FROM bill, bill_agents ".
"WHERE bill.agent_id = bill_agents.id AND YEAR(date) = YEAR(CURDATE()) AND MONTH(date) = MONTH(CURDATE()) ".
"GROUP BY bill.agent_id , DATE(bill.date) ".
"ORDER BY bill.date ASC ";
$result4 = mysql_query($query4) or die('Error, query failed1');
if (mysql_num_rows($result4)>0){
mysql_data_seek($result4, 0);
?>
<?php $total_1 = 0; while($row4 = mysql_fetch_array($result4, MYSQL_ASSOC)){?>
<?php $date = $row4['date'];
$var = $date;
$date = date("d-m-Y", strtotime($var) );
$date=substr($date, 0, -8);
echo $date;
?>
<tr>
<td><?php echo $row4['name']; ?></td>
<?php
for ($i=01; $i<=31; $i++)
{?>
<td><?php if ($date == $i) echo $row4['total']; ?></td>
<?php
}
?>
<td></td>
</tr>
<?php } } ?>
<tr>
<td colspan="31"></td>
<td>Total</td>
<td></td>
</tr>
</table>
我想要创建的是,如果数据库中有多个条目,我不想重复代理名称,它应该只属于当前日期,总计也应该是。怎么可能 sql 查询?还是我需要用其他代码创建?