如何获得过滤数据的总和

时间:2013-12-25 07:09:27

标签: mysql sql select group-by where-clause

我是php,mysql的新手。

我使用了四列,companynameissuedwtreceiptwt&我的数据库中workloss

我使用以下查询来获得已发行的wtwt,receiptwt& workloss。

$result = mysql_query("SELECT SUM(issuedwt) AS IssuedTotal, SUM(receiptwt) AS ReceiptTotal, SUM(workloss) AS Balance FROM `worksheet`")
or die(mysql_error());

我想使用基于companyname的过滤选项。(即company1,company2,company3)

如果我过滤company1,我只需要company1。我该怎么办?

4 个答案:

答案 0 :(得分:2)

您只需使用companyname子句过滤WHERE

SELECT  
  SUM(issuedwt) AS IssuedTotal, 
  SUM(receiptwt) AS ReceiptTotal,
  SUM(workloss) AS Balance 
FROM `worksheet`
WHERE compamnyname = 'company1' -- for example

这将仅为IssuedTotal提供ReceiptTotalBalancecompany1


但是,如果您想获得companyname和总计的列表,请使用GROUP BY companyname,但您仍然可以过滤公司名称:

SELECT companyname, 
  SUM(issuedwt) AS IssuedTotal, 
  SUM(receiptwt) AS ReceiptTotal, 
  SUM(workloss) AS Balance 
FROM `worksheet`
GROUP BY companyname

答案 1 :(得分:1)

在查询中添加“group by”选项将让mysql知道哪些元素属于一起,并且它将计算每组的总和:

"SELECT 
  SUM(issuedwt) AS IssuedTotal, 
  SUM(receiptwt) AS ReceiptTotal, 
  SUM(workloss) AS Balance 
  FROM worksheet 
  group by companyname"

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

您可以随时使用“where”选项限制显示哪些公司,(从TABLE中选择COLUMN = VALUE)但我假设您想要获取每个公司的数据;然后只使用分组。

答案 2 :(得分:0)

试试这个:

SELECT SUM(issuedwt) AS IssuedTotal, SUM(receiptwt) AS ReceiptTotal, 
       SUM(workloss) AS Balance 
FROM `worksheet`
WHERE companyname = 'company1';

如果您想要公司明智的数据而不是使用以下查询:

SELECT companyname, SUM(issuedwt) AS IssuedTotal, SUM(receiptwt) AS ReceiptTotal, 
       SUM(workloss) AS Balance 
FROM `worksheet`
GROUP BY companyname;

答案 3 :(得分:0)

使用GROUP BY子句和您的查询:

SELECT companyname, SUM(issuedwt) AS IssuedTotal, SUM(receiptwt) AS ReceiptTotal,
SUM(workloss) AS Balance FROM `worksheet`
GROUP BY companyname