Click here to Skip to main content
14,421,065 members
Rate this:
Please Sign up or sign in to vote.
See more:
Currently i'm starting a new project for a delivering service.

I have this table given:

CustID MealID Week  Weekday
1	   3	  1	Monday
1	   5	  1	Tuesday
1	   6	  1	Wednesday
1	   6	  1	Thursday
1	   3	  1	Friday
1	   5	  1	Saturday
1	   1	  2	Monday
1	   9	  2	Tuesday
1	  11	  2	Wednesday
1	  12	  2	Thursday
1	  12	  2	Friday
1	   1	  2	Saturday
2	   3	  1	Monday
2	   5	  1	Tuesday
2	   6	  1	Wednesday
2	   6	  1	Thursday
2	   3	  1	Friday
2	   5	  1	Saturday


In the first step i need all meals from Week 1. So a where clause works perfectly.
Now i have a second step. I need the count of each meal cumulated.

Let me say Meal 6 x 4, Meal 3 x 4 and so on.

Exists a good way to cumulate this?

What I have tried:

I tried out a count clause, but what i've seen, it doesn't works for that case.
Posted
Updated 5-Jun-19 2:49am
Comments
Patrice T 5-Jun-19 7:29am
   
And you plan to show the query you used ?
Rate this:
Please Sign up or sign in to vote.

Solution 1

You need to look at GROUP BY: SQL GROUP BY Statement[^]
Try:
SELECT MealID, COUNT(MealID) FROM MyTable
WHERE Week = 1
GROUP BY MealID
   
Comments
Sascha Manns 5-Jun-19 8:34am
   
Thanks for all for trying to help. I'll try this solution. Thanks @all.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Instead of using a WHERE clause PARTITION your data OVER Clause (Transact-SQL) - SQL Server | Microsoft Docs[^] and get all the information you need in a single query.

Here is the example from the link
USE AdventureWorks2012;  
GO  
SELECT SalesOrderID, ProductID, OrderQty  
    ,SUM(OrderQty) OVER(PARTITION BY SalesOrderID) AS Total  
    ,AVG(OrderQty) OVER(PARTITION BY SalesOrderID) AS "Avg"  
    ,COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS "Count"  
    ,MIN(OrderQty) OVER(PARTITION BY SalesOrderID) AS "Min"  
    ,MAX(OrderQty) OVER(PARTITION BY SalesOrderID) AS "Max"  
FROM Sales.SalesOrderDetail   
WHERE SalesOrderID IN(43659,43664);  
GO  
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100