-- sales report - task 2
-- changes:
--   removed menu name, because I assumed that Little lemon wants orders à la carte instead of fixed menus
--   changed cost cutoff from 150.00 to 75.00, because I wanted more than one test result
with
GroupedOrderItems as (
    select
        OI.OrderID,
        MI.Category,
        concat(MI.Name, " (", count(OI.OrderItemID), "x)") as Item
    from OrderItems as OI
    inner join MenuItems as MI on OI.MenuItemID = MI.MenuItemID
    group by OI.OrderID, MI.Category, OI.MenuItemID
),

MainOrderItems as (
    select
        OrderID,
        group_concat(Item separator '\n') as Items
    from GroupedOrderItems
    where Category = "Main"
    group by OrderID
),

StarterOrderItems as (
    select
        OrderID,
        group_concat(Item separator '\n') as Items
    from GroupedOrderItems
    where Category = "Starter"
    group by OrderID
)

select
    C.CustomerID,
    concat(C.FirstName, " ", C.LastName) as FullName,
    O.OrderID,
    O.BillAmount as Cost,
    coalesce(MOI.Items, "") as Mains,
    coalesce(SOI.Items, "") as Starters
from Orders as O
inner join Bookings as B on O.BookingID = B.BookingID
inner join Customers as C on B.CustomerID = C.CustomerID
left join MainOrderItems as MOI on O.OrderID = MOI.OrderID
left join StarterOrderItems as SOI on O.OrderID = SOI.OrderID
where O.BillAmount > 75.00
group by O.OrderID;
