簡體   English   中英

使用PHP和mysql有條件地對GROUP BY和COUNT進行多個

[英]Multiple conditionally GROUP BY and COUNT using PHP and mysql

首先,對於我的英語不好,我很抱歉,由於我使用手機並且我的代碼在我的辦公室PC上,所以沒有提供該代碼。 我一直在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 count by itemid不只一個。 我希望有一個人可以幫助我。

我會試一試。 選擇狀態非常棘手,因此我使用了MAX函數。

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

我不知道該怎么解釋...我只是嘗試嘗試並從@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM