简体   繁体   中英

group_concat values greater than specific value

Situation:

there are two tables, Head and Item , where each Head is related to one or more Items. I want to display the sum of each Items quantity per Item, per Month, as well as a list of all quantities that are greater than a specific value.

Head:

| OrderID | Timestamp | <several other columns> |
-------------------------------------------------
|       1 |   6548972 | ...                     |
|      10 |   6548978 | ...                     |
|     ... |       ... | ...                     |
-------------------------------------------------

Item:

| ItemId | OrderID | Quantity | <several other columns> |
---------------------------------------------------------
|     21 |       1 |        5 | ...                     |
|     22 |       1 |        3 | ...                     |
|     25 |      10 |        1 | ...                     |
|    ... |     ... |      ... | ...                     |
---------------------------------------------------------

Query:

SELECT
    SUM(Item.Quantity) AS `total`,
    GROUP_CONCAT(Item.Quantity ORDER BY Item.Quantity DESC SEPARATOR ', ') AS `quantities`,
    FROM_UNIXTIME(Head.Timestamp, '%m') AS `month`,
    COUNT(Head.OrderID) AS `orders`,
    Item.ItemID,
FROM
    Item LEFT JOIN (Head) ON (Head.OrderID = Item.OrderID)
WHERE
    (Head.Timestamp BETWEEN <sometime> AND <someothertime>)
GROUP BY
    `month`,
    Item.ItemID
ORDER BY
    `total` ASC

My work:

given the above situation and the query i was able to achieve my goals except that GROUP_CONCAT gives a list of all quantities, which is undesired. Instead I want all quantities displayed that are greater let's say 4

Current result:

| total | quantities | month | orders | ItemID |
------------------------------------------------
|     8 | 5, 2, 1    |    04 |      3 |     21 |
|     3 | 3          |    04 |      1 |     22 |
|    20 | 10, 9, 1   |    04 |      3 |     25 |

Desired result:

| total | quantitiesGreater4 | month | orders | ItemID |
--------------------------------------------------------
|     8 | 5                  |    04 |      3 |     21 |
|     3 |                    |    04 |      1 |     22 |
|    20 | 10, 9              |    04 |      3 |     25 |

Final question:

Is there a way to modify the original query to display the desired result? Or would this kind of work better be performed by my php script?

Update: I don't want the quantities <= 4 to be filtered out of total, i just don't want them in the quantities-list

Modify your GROUP_CONCAT clause as follows:

GROUP_CONCAT(
    IF(Item.Quantity > 4, Item.Quantity, NULL)
    ORDER BY Item.Quantity DESC SEPARATOR ', '
)

This works because GROUP_CONCAT() ignores NULL values .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM