I have a problem that's driving me crazy. i have a table that is a series of things like this -
(Unit type) (part description) (count)
-
IWU High pressure flowmeter 3
-
IWU Transformer 2
-
IWU Fender 2
-
GEN Fender 2
-
GEN Antifreeze 2
-
GEN Connection 1
-
60A Relief valve 1
-
60A High Pressure flow 1
There's a lot more values but you get the idea. I want to get the 5 most used parts per unit. The problem is, when i use the Select top 5 code it keeps giving me more records than I want where the 5th one has the same number as the next few records. Example: It works when the top 5 are 6 5 4 3 2 and the next highest is 1 but doesn't work when the top 5 are 5 4 3 2 1 and the next highest is 1. I have it organized descending by group so I really don't need it to look at the numbers. I just need it to pick the top 5 rows for each group and I can't get it to do that. I'm desperate! - SELECT tblIncidentByPartStep4.UnitType,
-
tblIncidentByPartStep4.PartDescription,
-
tblIncidentByPartStep4.New,
-
tblIncidentByPartStep4.Count
-
-
FROM tblIncidentByPartStep4
-
-
WHERE (((tblIncidentByPartStep4.Count) In (
-
SELECT top 5 Count
-
FROM tblIncidentByPartStep4 AS Dupe
-
WHERE dupe.Unittype = tblincidentByPartStep4.UnitType
-
ORDER BY dupe.count desc )));
6 15644 FishVal 2,653
Recognized Expert Specialist
Hello, linzeyd.
The problem is that the table has no primary key or any other unique field.
Add one and change WHERE clause in main query to check whether the unique field is within TOP 5 subset returned by the subquery.
Regards,
Fish
FishVal 2,653
Recognized Expert Specialist
Actually, after a preliminary testing, appears that even with PK field Access db engine shows definite flaws in certain combinations of TOP predicate and ordering by a field having duplicates.
I think it relates to query execution order internal optimizations, because TOP predicate works well with already ordered subquery: -
SELECT TOP .. * FROM (SELECT * FROM <table> WHERE ... ORDER BY ...);
-
Having played a little with it I would say that SQL/VBA hybride would be preferrable.
Names in example below are slightly different but I guess quite recognizible.
[keyID] is PK field - Autonumber(Long ), but could be any unique field of any type.
Code module: -
Public Function IsInTop(varPK As Variant, varUnitType As Variant, lngTopCount As Long) As Boolean
-
-
Dim rs As New ADODB.Recordset
-
-
If IsNull(varPK) Or IsNull(varUnitType) Then Exit Function
-
-
With rs
-
.ActiveConnection = CurrentProject.Connection
-
.CursorType = adOpenForwardOnly
-
.LockType = adLockReadOnly
-
.Open "SELECT keyID FROM t WHERE txtUnitType='" & varUnitType & _
-
"' ORDER BY lngCount DESC;"
-
For i = 1 To lngTopCount
-
If !keyID = varPK Then IsInTop = True: GoTo ExitPoint
-
.MoveNext
-
Next i
-
ExitPoint:
-
.Close
-
End With
-
-
Set rs = Nothing
-
-
End Function
-
Query: -
SELECT t.*
-
FROM t
-
WHERE IsInTop(t.keyID, t.txtUnitType,5);
-
NeoPa 32,569
Recognized Expert Moderator MVP
Actually, this behaviour is by design. The subquery, in which the TOP predicate is used, will return all records where the TOP 5 found values match. It does not guarantee to return only five records.
Furthermore, even had it returned only 5 records (a level of random guessing would be needed to determine which to select as the SQL doesn't specify), the values would be the same list of values anyway. This means that your SQL would STILL show however many records match those top 5 values, regardless of how many are returned in the subquery.
To avoid this behaviour (not very straightforward I'm afraid), add another field (preferably something unique) to the ORDER BY clause and then include this also within the WHERE clause of the main SQL.
There's more than one way to do this, but I'll include an example to illustrate : - SELECT [UnitType],
-
[PartDescription],
-
[New],
-
[Count]
-
-
FROM tblIncidentByPartStep4
-
-
WHERE [Count] & [PartDescription] In(
-
SELECT TOP 5 [Count] & [PartDescription]
-
FROM tblIncidentByPartStep4 AS Dupe
-
WHERE Dupe.UnitType=tblincidentByPartStep4.UnitType
-
ORDER BY [Count] DESC,
-
[PartDescription])
FishVal 2,653
Recognized Expert Specialist
Actually, after a preliminary testing, appears that even with PK field Access db engine shows definite flaws in certain combinations of TOP predicate and ordering by a field having duplicates.
I think it relates to query execution order internal optimizations, because TOP predicate works well with already ordered subquery: -
SELECT TOP .. * FROM (SELECT * FROM <table> WHERE ... ORDER BY ...);
-
;)
Actually that is well-known and even specified behavior.
It is not a bad idea to RTFM sometimes. TOP n [PERCENT]
Returns a certain number of records that fall at the top or the bottom of a range specified by an ORDER BY clause. Suppose you want the names of the top 25 students from the class of 1994: -
SELECT TOP 25
-
FirstName, LastName
-
FROM Students
-
WHERE GraduationYear = 1994
-
ORDER BY GradePointAverage DESC;
-
If you do not include the ORDER BY clause, the query will return an arbitrary set of 25 records from the Students table that satisfy the WHERE clause. The TOP predicate does not choose between equal values. In the preceding example, if the twenty-fifth and twenty-sixth highest grade point averages are the same, the query will return 26 records.
Regards,
Fish
NeoPa 32,569
Recognized Expert Moderator MVP
;)
Actually that is well-known and even specified behavior.
It is not a bad idea to RTFM sometimes.
Regards,
Fish
Just to make this clear - Fish was talking to himself when he said this.
@Linzey, this was not directed at you at all.
@Fish, we can't know all things all the time. We get rusty on things sometimes. I know I did (and do).
FishVal 2,653
Recognized Expert Specialist
Just to make this clear - Fish was talking to himself when he said this.
Just to make this absolutely clear - fishes don't talk at all. :P
Especially with human beings.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Irlan agous |
last post by:
Hello
i have t tables reactie and form and this query
$sql = "select reactie.persid,form.oproep,form.foto,form.id from
reactie,form
INNER JOIN reactie ON (reactie.persid = form.id) group by reactie.persid
order by reactie.persid DESC LIMIT 0,5";
$result = mysql_query($sql);
|
by: Randell D. |
last post by:
Folks,
I have a SELECT that returns with multiple records - It works when I have a
LIMIT clause but when I try to include a GROUP BY clause, the select returns
nothing (ie no records, no errors).
The GROUP BY specifies a column that does exist in my db (and is also the
only field that is select from the db).
Where am I going wrong? Because my select uses hashes (which I provide with
|
by: Tcs |
last post by:
My backend is DB2 on our AS/400. While I do HAVE DB2 PE for my PC, I haven't
loaded it yet. I'm still using MS Access. And no, I don't believe this is an
Access question. (But who knows? I COULD be wrong... :) I've tried the
access group...twice...and all I get is "Access doesn't like ".", which I know,
or that my query names are too long, as there's a limit to the length of the SQL
statement(s). But this works when I don't try to...
|
by: areef.islam |
last post by:
Hi, I am kinda new to javascript and I am having this problem with
selecting multiple options from a select tag. Hope someone can help me
out here.
here is my code
///////////////////////////////////////////////////////////////////////////////////////
<form action="whatever.php" method="post">
<select name="zip_code"
onchange="makeRequest('getCity.php?state='+this.form.zip_code.options.value)"
multiple="multiple" size="20">
|
by: bhanab |
last post by:
Hello,
Please can someone help me with this select statement? How do I get the statement to keep the week number static? ie if there are no values then it should show up as NULL, zero or just stay blank.
This is the statment :--
Select a., b., c., d., e.
From (SELECT Weeknum
FROM ..
Group by Weeknum)
| |
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=" & msDbFilename
moConn.Properties("Persist Security Info") = False
moConn.ConnectionString = msConnString
moConn.CursorLocation = adUseClient
moConn.Mode = adModeReadWrite' or using default...same result
|
by: Simon Gare |
last post by:
Hi,
trying to retrieve postal codes from the db but only want the query to look
at the first 3 digits of the code tried using
(LEFT(dbo.booking_form.COLL_POST_CODE),3) but that doesn't work. I don't
want the query to count individual post codes but instead look at an area
found in the first 3 digits e.g. HA0 3TD is for a particular house but HA)
is for the area Harrow.
|
by: Jon Bilbao |
last post by:
I´m trying a select clause in two steps because it´s too complex.
First:
SELECT Reference, Results.idEnsayo, Results.Num_taladro, min(Results.dTime)
+ 500 AS tIni, max(Results.dTime) - 500 AS tLast
FROM Results INNER JOIN Ensayos ON Results.idEnsayo=Ensayos.idEnsayo
WHERE (Ensayos.Reference=9)
GROUP BY Reference, Results.idEnsayo, Num_Taladro;
|
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 "interface" in Access. It's like a little system to make a production plan. It must get information about part numbers, description, set where the part number belongs, quantity of part numbers that the set uses, stock number(this is a text value, it...
|
by: The.Daryl.Lu |
last post by:
Hi,
Have a bit of a problem... I've created a form in Access and will use
the form for a user to query a table based on the selected fields.
The problem lies in that I was using checkboxes for the fields and
noticed that if I don't check a box, then the query will look
specifically in the table for where the applicable field is FALSE.
This isn't right however and decided that I should use a radio button
group so that the user can select...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |