Jump to content

Group by query unless column=1


biggieuk

Recommended Posts

Hi all,

 

I have a SQL statement which selects all records from a table, groups them by product_code, product_colour & product_size. I have added a new column 'admin'. I need to alter the query to return the items like before but only group the items that have 'admin' set to 0.

 

Is this possible in one single query?

 

SELECT *, SUM(quantity) as item_quantity
FROM orders_items
WHERE orders_id="1" 
GROUP BY  code, sizes_id, sizes_id_2, colours_id
ORDER BY id ASC

 

Thanks for help with this

Link to comment
https://forums.phpfreaks.com/topic/252565-group-by-query-unless-column1/
Share on other sites

Hi

 

Bit uncertain what you want to count.

 

You could just add the admin column to the group by. This would give you a row for admin = 0 and a row for admin = 1 for each set of data which contained both.

 

You could do something like this:-

 

SELECT *, SUM(IF(admin = 1, 0, quantity)) as item_quantity
FROM orders_items
WHERE orders_id="1" 
GROUP BY  code, sizes_id, sizes_id_2, colours_id
ORDER BY id ASC

 

All the best

 

Keith

thanks for your reply, I think my explanation could have been better.

 

Basically I am currently returning rows like so:

 

code

colour

size

quantity

admin

123

2

34

1

0

143

6

23

3

0

145

8

37

1

0

 

The query is grouping the rows by code, size and colour then counting the quantity column.

 

I need the query to group the results like above but only if the admin column is 0.  If admin is 1 then just output the row without grouping  like so:

 

code

colour

size

quantity

admin

123

2

34

1

0

143

6

23

1

1

143

6

23

1

1

143

6

23

1

1

145

8

37

1

0

 

 

Is that any clearer?

Hi

 

It is, and not sure there is an elegant way to do it.

 

Best way I can think would be 2 queries UNIONed together, one for the admin and one for the non admin rows.

 

Something like (please excuse any typos):-

 

SELECT *, SUM(quantity) as item_quantity
FROM orders_items
WHERE orders_id="1" 
AND admin = 0
GROUP BY  code, sizes_id, sizes_id_2, colours_id
UNION ALL
SELECT *, quantity as item_quantity
FROM orders_items
WHERE orders_id="1" 
AND admin = 1

 

All the best

 

Keith

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.