473,419 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,419 software developers and data experts.

select sort and group by

My database record is as below:-

Expand|Select|Wrap|Line Numbers
  1. cartid  foodid   qty
  2. 92      5        1
  3. 93      5        1
  4. 94      5        1
  5. 95      11       1
  6. 96      5        1
  7. 97      5        1
Can it be arrange into this form?
Assume that the max sum(qty)=3

Expand|Select|Wrap|Line Numbers
  1. foodid   sum(qty)
  2. 5        3
  3. 11       1
  4. 5        2
Aug 25 '10 #1
13 2717
gpl
152 100+
Are you saying that you want a query like:
Expand|Select|Wrap|Line Numbers
  1. Select foodid, Sum(qty)
  2. from Mytable
  3. Group by foodid
But that if the quantity exceeds 3 you want to show a new grouping ?
It is possible, but why ?
Aug 25 '10 #2
this method i had tried. Couldn't help.
The reason quantity set to 3 is because i limit the chief to cook the food limit to 3 quantities only...
Aug 25 '10 #3
Jerry Winston
145 Expert 100+
I'm intrigued by your data requirement.

Can you elaborate on the purpose of the other fields?
  • Is one Order(107) a group of servings (1,1,1,1,1) of a particular type of food? (5,5,5,11,5)?
  • What purpose does cartid serve? What does it track?
  • Will the qty field always be 1--since you don't record the infinite 0 servings served and each serving gets it's own entry?
  • Is the purpose of this query to find instances where cooks prepared more than 3 servings at a time?
Aug 25 '10 #4
Sorry for that. You can ignore the orderid.
Foodid is the food type.
Yes. The quantity always will be 1.
Yes. The purpose of this query to find instances where cooks prepared more than 3 servings at a time
Aug 25 '10 #5
gpl
152 100+
this solution makes use of a tally table

define a tally table
Expand|Select|Wrap|Line Numbers
  1. IF EXISTS (SELECT *
  2.            FROM   Dbo.Sysobjects 
  3.            WHERE  Id = Object_id(N'[dbo].[Tally]') 
  4.                   AND Objectproperty(Id, N'IsUserTable') = 1) 
  5.   DROP TABLE [dbo].[Tally]
  6. GO 
  7.  
  8. CREATE TABLE [dbo].[Tally] 
  9.   ( 
  10.      [TallyNum] [INT] NOT NULL 
  11.   ) 
  12. ON [PRIMARY]
  13. GO 
  14.  
  15. ALTER TABLE [dbo].[Tally] ADD CONSTRAINT [PK_Tally] PRIMARY KEY CLUSTERED ( 
  16. [TallyNum] ) WITH FILLFACTOR = 100 ON [PRIMARY]
  17. GO 
  18.  
  19. --- Fill table with all values
  20.  
  21. Insert Into [dbo].[Tally] ([TallyNum]) Values (0)
  22. Insert Into [dbo].[Tally] ([TallyNum]) Values (1)
  23. Insert Into [dbo].[Tally] ([TallyNum]) Values (2)
  24. Insert Into [dbo].[Tally] ([TallyNum]) Values (3)
  25. Insert Into [dbo].[Tally] ([TallyNum]) Values (4)
  26. Insert Into [dbo].[Tally] ([TallyNum]) Values (5)
  27. Insert Into [dbo].[Tally] ([TallyNum]) Values (6)
  28. Insert Into [dbo].[Tally] ([TallyNum]) Values (7)
  29. Insert Into [dbo].[Tally] ([TallyNum]) Values (8)
  30. Insert Into [dbo].[Tally] ([TallyNum]) Values (9)
  31.  
  32.  
now query utilising the tally table
Expand|Select|Wrap|Line Numbers
  1. DECLARE @MAXCOUNT INT
  2. SET @MAXCOUNT = 3
  3.  
  4. --- pull out the data
  5. SELECT Foodid, 
  6.        @MAXCOUNT 
  7. FROM   ( (SELECT Foodid,
  8.                Sum_qty / @MAXCOUNT AS Count_sum_qty 
  9.         FROM   (SELECT Foodid, 
  10.                        SUM(Qty) AS Sum_qty 
  11.                 FROM   Mytable 
  12.                 GROUP  BY Foodid) S1 
  13.         WHERE  S1.Sum_qty / @MAXCOUNT > 0) s2
  14.          JOIN (SELECT DISTINCT CONVERT(INT, 
  15.                                              CONVERT(VARCHAR(1), T1.Tallynum) +
  16.                                              CONVERT(VARCHAR(1), T2.Tallynum) + 
  17.                                              CONVERT(VARCHAR(1), T3.Tallynum)
  18.                                       ) AS Numbervalues
  19.                FROM   Dbo.Tally T1, 
  20.                       Dbo.Tally T2, 
  21.                       Dbo.Tally T3) A 
  22.            ON A.Numbervalues < Count_sum_qty -- tally count starts at 0, so not LE
  23.        )
  24. UNION ALL 
  25. --- find all the remainders (where the sum is less than the max value allowed) 
  26. SELECT Foodid, sum_qty % @MAXCOUNT
  27. FROM 
  28. (
  29.   SELECT Foodid,
  30.          SUM(Qty) as sum_qty
  31.   FROM   Mytable
  32.   GROUP  BY Foodid
  33.   HAVING SUM(Qty) % @MAXCOUNT BETWEEN 1 AND @MAXCOUNT
  34. ) s2
you would need to wrap the above query into a stored proc, to allow for the variable maxcount.

If you are sure the chefs limit is 3, then extract the query from after the 'pull out the data comment'
and replace @MAXCOUNT with the real maximum, 3

good luck
Graham
Aug 25 '10 #6
ck9663
2,878 Expert 2GB
If you're just trying to see which foodid was prepared three or more times, would a:

Expand|Select|Wrap|Line Numbers
  1.  
  2. Select o.foodid, f.foodname, count(*)
  3. from Mytable o
  4. left join YourFoodTable f on o.foodid = f.foodid
  5. Group by o.foodid, f.foodname
  6. having count(*) > 2
  7.  
  8.  
work?

The left join was thrown in to identify the food name. That is if you have a table for your food containing the description, etc...

Good Luck!!!

~~ CK
Aug 25 '10 #7
Not working... It just show 2 rows only.

GPL: I still trying on your solution ;) It quite new to me. I trying on it. Thx lots
Aug 25 '10 #8
Jerry Winston
145 Expert 100+
@ maniacCow
It only shows two row because you asked us to discard orderID and cartid as unimportant so your data set looks like this?:
Expand|Select|Wrap|Line Numbers
  1. foodid   qty
  2. 5        1
  3. 5        1
  4. 5        1
  5. 11       1
  6. 5        1
  7. 5        1
If this is true, I'm quite positive it is impossible to calculate how many servings a cook prepared in a session.
Why:
There is no data available to define the concept of a "cooking session". The table above only tells you that you cooked n foods of type x. The qty column is unnecessary as each row,by design, asserts that 1 and only 1 serving of x was created as you stated above. Therefore, the only data we have to go on is this:
Expand|Select|Wrap|Line Numbers
  1. foodid  
  2. 5        
  3. 5        
  4. 5        
  5. 11       
  6. 5        
  7. 5
We cannot rely on the INSERT sequence of the rows to establish cooking sessions because we have nothing to ORDER BY.

I may have missed interpreted your requirement or it's over my head. I'll need more data in order to do any meaningful analysis.
Aug 25 '10 #9
gpl
152 100+
Just say if you want me to talk you through it
Graham
Aug 25 '10 #10
Jerry Winston
145 Expert 100+
@gpl

You do realize your solution doesn't record instances where the cook prepared more than 3 servings right? Per user requirement stated in maniacCow's post #5 you'd need to modify your solution to find the per instance count of servings prepared by the cook then find the instances greater than 3. The problem with your solution, is that it erroneously reports a chef that cooks 2 servings of x then cooks another 4 servings of X as having prepared 3 servings of x twice.


If I'm still failing to see your solution please do talk me through this.
Aug 25 '10 #11
gpl
152 100+
Jerry
In post #3, maniacCow stated that it was a business rule that 3 was the limit that the chief (chef?) was allowed.

I dont believe the order of insertion is relevant (Id hope not as it is meaningless in a table).

If the cartid does determines a sequence, then you are right, my solution would not work in the scenario that you describe and a cursor or client-side application would have to do the calculation.

It does assume that the data is clean and no error has allowed the business rule to be broken.

Looking through the posts, post #5 says the qty will always be 1, you could use the presence of the record to indicate this and do a count instead of a sum.

I realise that in my long query, the line
Expand|Select|Wrap|Line Numbers
  1. HAVING SUM(Qty) % @MAXCOUNT BETWEEN 1 AND @MAXCOUNT
  2.  
could more sensibly be replaced with
Expand|Select|Wrap|Line Numbers
  1. HAVING SUM(Qty) % @MAXCOUNT > 0
This is the trouble with trying to solve an issue when the complete problem domain is not described, and thus incorrect or incomplete solutions are given.
Aug 25 '10 #12
Jerry Winston
145 Expert 100+
@mainiacCow

Can you share with us what is the purpose of the cartid field? Can you confirm this requirement from post #5?:

"The purpose of this query to find instances where cooks prepared more than 3 servings at a time"

@gpl

You're right, it's very tough to hit a moving target on-the-fly with a piece of code on the first. I thought I was over looking something.
Aug 25 '10 #13
NeoPa
32,556 Expert Mod 16PB
maniacCow:
Sorry for that. You can ignore the orderid.
I would guess that this comment is unreliable for two reasons.
  1. OrderID has never been introduced into the conversation in the first place. I suspect the reasonable guess that they were intending to refer to CartID is absolutely correct, however it does indicate a lack of precision and, by inference, a lack of appreciation for any more complicated detail.
  2. From 1 above, and also the general level of understanding exhibited in the replies, I would say this statement was made due to a lack of appreciation of where that data might fit in to a solutioon.
I would say the CartID is actually the data required to determine which order the servings appear in, and should certainly be used as part of any workable solution.
Aug 26 '10 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: James P. | last post by:
Hello, I have a report with the Priority field is used as sort order and grouping. The problem is the data in this Priority field if sorted in ascending order is: High, Low, and Medium. How...
12
by: Gerrit Beuze | last post by:
Hi all, I'm wondering if you how you organize as (in sorting / order) your C# class code: Do you sort/ group by member type: fields, methods, properties etc.? If yes: what ordering scheme do...
8
by: Thomas | last post by:
Hi! I´m a newbie with this and I´m trying to build a forum of my own but have stumbled on my first problem as early as the opening page. To the problem: I want to show a simple forum layout...
22
by: MP | last post by:
vb6,ado,mdb,win2k i pass the sql string to the .Execute method on the open connection to Table_Name(const) db table fwiw (the connection opened via class wrapper:) msConnString = "Data Source="...
10
by: Jim Andersen | last post by:
I have this xml-file. I want to sort it, and create a new xml-file. The result should be identical to the input except that it's sorted. <?xml version="1.0" encoding="UTF-8"?> <levelone> <child...
1
by: zafm86 | last post by:
Hi everyone! I'm sure my problem is pretty easy to solve but I've been working on it for a long and my my brain is not working correctly anymore. I'm working with an AS400 and I mhave to do an...
1
by: monicaj | last post by:
Hi, Can anyone suggest - what are the alternative means I achieve following functionality - select x , y from table1 group by x since rules say group by clause needs all listed fields in...
1
by: inamul | last post by:
I want to select CheckBox based on data retrieved from mysql database table. Could anyone show me the simple way of doing it. Data store in table under colum "sectionOfInterest" is shown below...
0
by: =?Utf-8?B?UmF2aSBTaGFua2Fy?= | last post by:
Hi, Is it possible to popup the User/Goup Selection dialog box as part of my application (VB.Net, VS2005) ? I wish to permit the user to select/assign existing User Accounts (local computer or...
5
by: dantebothermy | last post by:
Hi all, I have a form with a subform. On the form is a combo box with three choices "current", "former" and "all". I'd like to use that combo box to set the data source for the subform based on...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.