使用PHP和mysql多个有条件地GROUP BY和COUNT

时间:2015-07-20 14:20:38

标签: php mysql sql

首先,我很抱歉我的英语不好,很抱歉没有提供代码,因为我正在使用手机而我的代码在我的办公室电脑上。我一直在Google上搜索并尝试使用UNION,但结果并不像我预期的那样。请帮我解决这个问题。

我在mysql上有这个访问表:

| date              | merchant     | itemid |  act      | result |
|++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
| 2015-07-19        | 3G Power     | 100    | visit     | OK     |
| 2015-07-19        | 3G Power     | 101    | visit     | OK     |
| 2015-07-19        | Anamely      | 200    | visit     | OK     |
| 2015-07-19        | Anamely      | 201    | visit     | OK     |
| 2015-07-19        | Anamely      | 202    | visit     | NOK    |
| 2015-07-19        | Anamely      | 203    | repair    | NOK    |
| 2015-07-20        | Garden Bay   | 300    | visit     | OK     |
| 2015-07-20        | Garden Bay   | 301    | install   | OK     |
| 2015-07-20        | Anamely      | 203    | repair    | OK     |

这是我尝试的UNION

create view allvisit (date, merchant, act, result, itemqty) as
select date, merchant, act, 'OK', count(itemid) from visit where result='OK' group by merchant
union
select date, merchant, act, 'NOK', count(itemid) from visit where result='NOK' group by merchant

我在html表中的预期结果是:

| date              | merchant     |  act      | result | itemqty |
|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
| 2015-07-19        | 3G Power     | visit     | OK      | 2      |
|                   | Anamely      | visit     | OK      | 2      |
|                   | Anamely      | visit     | NOK     | 1      |
|                   | Anamely      | repair    | NOK     | 1      |
| 2015-07-20        | Garden Bay   | visit     | OK      | 1      |
|                   | Garden Bay   | install   | OK      | 1      |
|                   | Anamely      | repair    | OK      | 1      |
|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
|     total work day.               | 2 days | tot qty| 9 items   |
|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|

因此条件是日期仅显示在每个相同日期的第一列和第一行,商家名称仅显示每个act和结果,并使用count by itemid => itemqty不止一个。我希望有人可以帮助我。

2 个答案:

答案 0 :(得分:1)

我会试一试。选择状态很棘手,所以我使用了MAX功能。

select
  MIN(date),
  merchant,
  act,
  MAX(result),
  count(itemid) as itemqty
from MYTABLE 
GROUP BY merchant, act

答案 1 :(得分:0)

我不知道如何解释......我只是尝试从@beiller回答编辑错误...

这是我的预期结果的SQL工作:

create view allvisit (date, merchant, act, result, itemqty) as
select min(date) as date, merchant, act, 'OK', count(itemid) from visit where result='OK' group by merchant,act
union
select min(date) as date, merchant, act, 'NOK', count(itemid) from visit where result='NOK' group by merchant,act