Frage

Let's say this is my DB table: id, client_id, order_name

Every doubled order is creating new record. For example:

1, 1, super-glue
2, 1, super-glue
3, 1, plastic wallet

How do I found in single query, how many different items client ordered?

So it will return me 2 in this case.

I know I have to use SELECT {something in here} WHERE client_id = 1 But I'm not sure about how to count different items.

War es hilfreich?

Lösung 2

To just count the different items for one customer you can use

SELECT COUNT(DISTINCT order_name)
FROM orders
WHERE client_id=1;

If you want a summary count for every customer you can use a group by expression:

SELECT client_id, COUNT(DISTINCT order_name)
FROM orders
GROUP BY client_id;

If you want the latest row for every customer and order_name, you can use a subquery:

SELECT id, client_id, order_name
FROM
(
  SELECT max(id) AS id
  FROM orders
  GROUP BY client_id, order_name
) single_orders
INNER JOIN orders ON single_orders.id = orders.id
ORDER BY client_id, order_name;

This would select the maximum id for each distinct customer-order-combination and then get the corresponding row data.

Finally, in MySQL you can also get a comma-separated list of the distinct items ordered by any customer:

SELECT client_id, group_concat(DISTINCT order_name ORDER BY order_name)
FROM orders
GROUP BY client_id
ORDER BY client_id;

Andere Tipps

Use COUNT with DISTINCT order_name:

SELECT COUNT(DISTINCT order_name)
FROM yourTable
WHERE client_id = 1
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top