Good day,
I'm a fairly newbie in SQL.
Spent quiet some time surfing the Web searching for an answer to my problem... which I think is easy to solve for an experienced programmer.
I have a database containing 4 fields in the same table (Customer, Item, Order, DateSold).
The Item field could be either (pant, shirt, blazer, shoe).
Table name: Sales
I would like to have a query that will return only the Customers that have bought >=2 pants AND >=3 shirts in the month (could be bought separately on different order).
And that, for all 2021, (Group by month).
Help please.
Thank you.
I think "Order" seems equivalent to "Quantity" and that you wanted that total "Order" >= 2 / 3. If not, the code will need to be adjusted.
SELECT
Customer,
STUFF(CONVERT(varchar(11), DATEADD(MONTH, DATEDIFF(MONTH, 0, DateSold), 0), 100), 3, 3, '') AS MonthSold,
SUM(CASE WHEN Item = 'Pants' THEN [Order] ELSE 0 END) AS Pants,
SUM(CASE WHEN Item = 'Shirts' THEN [Order] ELSE 0 END) AS Shirts
FROM Sales
GROUP BY
Customer,
DATEADD(MONTH, DATEDIFF(MONTH, 0, DateSold), 0)
HAVING
SUM(CASE WHEN Item = 'Pants' THEN [Order] ELSE 0 END) >= 2 AND
SUM(CASE WHEN Item = 'Shirts' THEN [Order] ELSE 0 END) >= 3
ORDER BY
Customer,
DATEADD(MONTH, DATEDIFF(MONTH, 0, DateSold), 0)
Scott,many thanks for the fast response.
Tried the code this morning and I was not able to make it work. Got an error.
Simplified the query and got rid of the date as it was not so important.
The error I'm still getting is: "Syntax-error (missing operator) in expression "SUM(CASE WHEN [TypeCompte] = "HQ" THEN [Qtee] ELSE 0 END) AS HQ"
Yes, there are very many types of SQL. It's supposed to be a standard language, but there are many, many dialects among different dbms vendors. Kinda like there are many variations of English.