A
A
Adian2018-10-05 19:05:11
MySQL
Adian, 2018-10-05 19:05:11

MySQL - how to write a query with multiple SELECTs?

Let's say there is a table TBL1

box_namefruit_name
box1apple
box1orange
box2apple
box1tomato
box2tomato
 
As a result, it should turn out like this:
box_nametotal_fruitfruit_applefruit_orangefruit_tomato
box13oneoneone
box22one0one
 
Actually how to get the first two columns figured out, but how to add the rest?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nozzy, 2018-10-05
@Adian

SELECT
    box_name,  
    SUM(CASE WHEN (fruit_name='apple') THEN 1 ELSE 0 END) AS fruit_apple,
    SUM(CASE WHEN (fruit_name='orange') THEN 1 ELSE 0 END) AS fruit_orange,
    .... и тд
FROM 
    your_table
GROUP BY 
    box_name

A
Arman, 2018-10-05
@Arik

It looks like a topic on grouping data, you just need to group and calculate how much of what
total_fruit will probably have to be considered as a subquery either at the php level or whatever you have there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question