mysql - Group a table by if there is is isnt a matching record in joined table? -


i have table listing invoices group on year total following

select   sum(totalvalue/((100 + vat)/100)) purchases ,   year(invoice_date) invoiceyear invoices group year(invoice_date) order invoiceyear desc; 

we have list of invoice table includes link supplierid in list of suppliers , product table includes list of links supplierid

i need group on weather or not invoices stock orders or not, need group on fact there or not product matching supplierid

this im getting stuck, when run join im stuck on how group if supplierid field null or not null ??

also invoices multiple products how ensure im not creating multiple records in invoice table ?

assuming supplierid column called supplierid , each table has id column, here's answer:

select     sum(`totalvalue` / ((100 + `vat`)/100)) `purchases`,     `order_type`,     `invoice_year` (     select `i`.*,            if(count(`p`.`id`) = 0, 'custom', 'stock') `order_type`,         year(`i`.`invoice_date`) `invoice_year`     `invoices` `i`     left join `products` `p`          on `i`.`supplierid` = `p`.`supplierid`     group `i`.`id` ) `filtered` group `order_type`, `invoice_year` order `invoice_year` desc 

explanation: in order this, need left join on products table, grouping invoice id. count of product id return 0 or > 0 if there matching product or not.

we're putting in subquery because don't want count of products compounding outer grouping, cause issues in math if have more 1 product per invoice in cases (i.e. there many products same supplier id).


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -