473,407 Members | 2,320 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,407 software developers and data experts.

Select a distinct row per ID, but rather complicatedly.

8
Hi, all,

I have a data as follows.
ID t Status
1 0 Y
1 1 Y
1 2 Y
1 3 N
1 4 N
1 5 N
1 6 N
2 0 X
2 1 X
2 2 Y
2 3 Y
2 4 Z
3 0 Y
3 1 Y
3 2 Z
3 3 Z
3 4 Z
3 5 N
3 6 N
3 7 Y
3 8 Y
4 0 Y
4 1 Y
4 2 X


Assume I have the data above.
I want to create a query generating its result as follows.

ID Delta T
1 1 3
2 0 4
3 1 5
4 0 2.

More explanation of the rule is as follows.
Each ID has varying status X/Y/Z etc. and N.

Basically, want to select a row from each ID.
Once 'N' is observed at least once in the status field,
I want to define Delta(ID)=1. Otherwise =0.
In other words, I want Delta to be an indicator if there was any status 'N' in the history of the ID. Then want to let T be the first month the 'N' is observed.

If no 'N' is observed, I want Delta(ID)=0.
Then I want T to be the largest t observed.

I cannot create exactly what I really want for myself.
Please give me a help.

Thank you,

Joon
Sep 12 '08 #1
8 2080
I'm confused. Could you post a mathmatical formula of what exactly the transformation is supposed to be?
Sep 12 '08 #2
jooon3
8
Let Time(ID) be a set of available t's corresponding to the given ID.
(e.g. Time(ID=1) = {0,1,2,3,4,5,6}.)

If Status(ID, t)= "N" for some t in Time(ID), then

Delta(ID) := 1
T(ID) := min{t in Time(ID) : Status(ID, t) = "N"}.

Else (that is, if Status(ID, t)<> "N" for all t in Time(ID) ),

Delta(ID) := 0
T(ID) := max{t in Time(ID)}.


I don't know this is enough for you to understand.

Thank you,

Joon
Sep 12 '08 #3
Its better. Seems to me that you are trying to calculate answers for some variables. I'd separate it into multiple queries. Call the first your "N" query. Perform your first calculation.
min{t in Time(ID)}
Making sure to use the "WHERE" your field for your data ="N"

Then make a second query called your "Not N" query.
max{t in Time(ID)}.
Making sure to use the "WHERE" your field for your data <> "N"

Generally speaking when I do things like this (multiple level queries from the same data), I put the input data in one table and the output data in a second table. That way I can watch it better. Then after I make sure it works I steal the SQL code the program has made for me and run it from VBA or a macro. That way I can run the queries quicker in the future and never wonder, "Did I run both of those or just the first one?"
Sep 12 '08 #4
FishVal
2,653 Expert 2GB
Hello, jooon.

May be not the most elegant but a working one:

qryHasN
Expand|Select|Wrap|Line Numbers
  1. SELECT t.lngID, Min(t.lngT) AS T, Sgn(Sum(t.txtStatus="N")) AS blnDelta
  2. FROM t
  3. WHERE t.txtStatus="N"
  4. GROUP BY t.lngID
  5. HAVING Sgn(Sum(t.txtStatus="N"));
  6.  
qryHasNoN
Expand|Select|Wrap|Line Numbers
  1. SELECT t.lngID, Max(t.lngT) AS T, Sgn(Sum(t.txtStatus="N")) AS blnDelta
  2. FROM t
  3. GROUP BY t.lngID
  4. HAVING Not Sgn(Sum(t.txtStatus="N"));
  5.  
qryOverall
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM qryHasN
  2. UNION
  3. SELECT * FROM qryHasNoN;
  4.  
Regards,
Fish
Sep 12 '08 #5
jooon3
8
Thank you all.
I will try both. (they are possibly same?)
Then get back to you whether they work or not.
If not, I will ask another question.

Thank you again,

Joon
Sep 12 '08 #6
Stewart Ross
2,545 Expert Mod 2GB
Hi jooon3. I do not want to disrupt this thread as your question has kindly been answered by two posters, but does your question relate to a real requirement you are trying to implement, or is it instead taken from some form of homework assignment? The phrasing of your question, and in particular of your clarification in post 3, looks very like the phrasing of an assignment question of some kind to me.

If it is, please be aware that it is against our site rules to expect others to answer homework questions for you - our posting guidelines and FAQ are quite clear about this.

Of course it may be that you are simply solving a particular work-related problem - if this is the case the assistance you have received will be very welcome I am sure.

-Stewart
Sep 12 '08 #7
jooon3
8
I am sorry if my post was not appropriate in this forum. But it was none of HW.

I generated the simple data for my other project because the real data was confidential.
The post 3 was fully written by myself based on the rules I wanted to apply.

I was just new to MS-Access.
Sorry again if the question was too elementary.

Joon
Sep 20 '08 #8
ADezii
8,834 Expert 8TB
I am sorry if my post was not appropriate in this forum. But it was none of HW.

I generated the simple data for my other project because the real data was confidential.
The post 3 was fully written by myself based on the rules I wanted to apply.

I was just new to MS-Access.
Sorry again if the question was too elementary.

Joon
Here is an Algorithm that will produce the desired results in the Form of a Table (tblFinalResults), but first, two simple steps:
  1. Create a Table named tblTestData and populate it with your sample data, or simply rename your present Table, but maintain the following Data Types and Field Names:
    • [ID] - (INTEGER)
    • [t] - (BYTE)
    • [Status] - (TEXT 1)
  2. Create a Table and name it tblFinalResults:
    • [ID] - (INTEGER)
    • [Delta] - (BYTE)
    • [T] - (INTEGER)
  3. Create the following Public Function in a Standard Code Module:
    Expand|Select|Wrap|Line Numbers
    1. Public Function fGenerateResultSet() As Boolean
    2. Dim MyDB As DAO.Database
    3. Dim rstUniqueIDs As DAO.Recordset
    4. Dim rstResults As DAO.Recordset
    5. Dim strSQL As String
    6. Dim strSQL_2 As String
    7. Dim bytDelta As Byte
    8. Dim intT As Integer
    9.  
    10. fGenerateResultSet = False      'Initialize to False
    11.  
    12. Set MyDB = CurrentDb()
    13.  
    14. 'Used to generate 'Unique ID' Values in Ascending Order
    15. strSQL = "Select Distinct [ID] From tblTestData Order By tblTestData.[ID];"
    16. Set rstUniqueIDs = MyDB.OpenRecordset(strSQL, dbOpenForwardOnly)
    17.  
    18. Set rstResults = MyDB.OpenRecordset("tblFinalResults", dbOpenDynaset)
    19.  
    20. 'Delete any prior contents of the Table
    21. strSQL_2 = "Delete * From tblFinalResults;"
    22. CurrentDb.Execute strSQL_2, dbFailOnError
    23.  
    24. With rstUniqueIDs
    25.   Do Until .EOF
    26.     'N is observed for specified [ID]
    27.     If DCount("*", "tblTestData", "[Status] = 'N' And [ID] = " & ![ID]) > 0 Then
    28.       bytDelta = 1      'N was observed for [ID], min{t in Time(ID): Status(ID, t) = "N"}
    29.       intT = DMin("[t]", "tblTestData", "[Status] = 'N' And [ID] = " & ![ID])
    30.     Else
    31.       bytDelta = 0      'N was not observed for [ID], max{t in Time(ID}
    32.       intT = DMax("[t]", "tblTestData", "[ID] = " & ![ID])
    33.     End If
    34.       rstResults.AddNew
    35.         rstResults![ID] = ![ID]
    36.         rstResults![Delta] = bytDelta
    37.         rstResults![T] = intT
    38.       rstResults.Update
    39.       'Debug.Print ![ID] & " ==> " & bytDelta & " ==> " & intT      Test String
    40.     .MoveNext
    41.   Loop
    42. End With
    43.  
    44. 'If you've gotten this far, success
    45. fGenerateResultSet = True
    46.  
    47. rstResults.Close
    48. rstUniqueIDs.Close
    49. Set rstUniqueIDs = Nothing
    50. Set rstResults = Nothing
    51.  
    52. 'Finally, lets see the fruits of our labor
    53. DoCmd.OpenTable "tblFinalResults", acViewNormal, acReadOnly
    54. End Function
  4. Sample Function Call:
    Expand|Select|Wrap|Line Numbers
    1. If fGenerateResultSet() Then
    2.   MsgBox "Success!"
    3. Else
    4.   MsgBox "ADezii screwed things up again!"
    5. End If
  5. OUTPUT (tblFinalResults)
    Expand|Select|Wrap|Line Numbers
    1. ID    Delta    T
    2. 1      1    3
    3. 2      0    4
    4. 3      1    5
    5. 4      0    2
  6. Any questions, feel free to ask.
Sep 20 '08 #9

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

Similar topics

2
by: dr. zoidberg | last post by:
Hello, I'm trying to select all distinct years from a unixtimestamp field in MySQL database. I have a query: SELECT DISTINCT YEAR(date_field) As theYear FROM table but it gives me an empty...
5
by: Martin Feuersteiner | last post by:
Dear Group I'm having trouble with the clause below. I would like to select only records with a distinct TransactionDate but somehow it still lists duplicates. I need to select the...
5
by: Reestit Mutton | last post by:
Hi, I'm currently learning the ropes with CSS, PHP, MYSQL, Javascript etc... by redesigning my website as a database driven site. Okay, so I'm skilled at perl, data manipulation and data...
2
by: mfyahya | last post by:
I have two tables, both containing an 'authors' column. Is there a way to get a unique list of authors from the two tables? I tried SELECT DISTINCT `authors` from `table1`, `table2`; but I got an...
3
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...
8
by: skinnybloke | last post by:
Hi - I have a problem with a memo field being truncated to about 255 characters when running a Access 2002 query. This only seems to happen if I use SELECT DISTINCT. It works ok using SELECT by...
18
by: mathilda | last post by:
My boss has been adamant that SELECT DISTINCT is a faster query than SELECT all other factors being equal. I disagree. We are linking an Access front end to a SQL Server back end and normally are...
5
by: Daniel Wetzler | last post by:
Dear MSSQL experts, I use MSSQL 2000 and encountered a strange problem wqhile I tried to use a select into statement . If I perform the command command below I get only one dataset which has...
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="...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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...
0
agi2029
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,...
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.