Related Tables: Help Needed With JOIN Query

Oct 16, 2006

Hi Group,

My apologies for the lengthy post, but here goes...

I have the following tables:

TABLE Vehicles
(
[ID] nvarchar(5),
[Make] nvarchar(20),
[Model] nvarchar(20),
)

TABLE [Vehicle Status]
(
[ID] int, /* this is an auto-incrementing field*/
[Vehicle ID] nvarchar(5), /* foriegn key, references Vehicles.[ID] */
[Status] nvarchar(20),
[Status Date] datetime
)

Here's my problem...

I have the following data in my [Vehicles] and [Vehicle Status] tables:

[ID] [Make] [Model]
----------------------
H80 Nissan Skyline
H86 Toyota Aristo


[ID] [Vehicle ID] [Status] [Status Date]
----------------------------------------
1 H80 OK 2006-10-01
2 H80 Damage 2006-10-05
3 H86 OK 2006-10-13
4 H86 Dent 2006-10-15
5 H86 Scratched 2006-10-16

I need a query that will join the two tables so that the most recent
status of each vehicle can be determined. I've gotten as far as:

SELECT Vehicle.[ID], Make, Model, [Status], [Status Date] FROM
[Vehicles] INNER JOIN [Vehicle Status] ON [Vehicles].[ID] = [Vehicle
Status].[Vehicle ID]

Of course this produces the following results:

[ID] [Make] [Model] [Status] [Status Date]
--------------------------------------------
H80 Nissan Skyline OK 2006-10-01
H80 Nissan Skyline Damage 2006-10-05
H86 Toyota Aristo OK 2006-10-13
H86 Toyota Aristo Dent 2006-10-15
H86 Toyota Aristo Scratched 2006-10-16

How do I filter these results so that I get only the MOST RECENT vehicle
status?

i.e:

[ID] [Make] [Model] [Status] [Status Date]
--------------------------------------------
H80 Nissan Skyline Damage 2006-10-05
H86 Toyota Aristo Scratched 2006-10-16

Thanks in advance,
Rommel the iCeMAn

*** Sent via Developersdex http://www.developersdex.com ***

View 1 Replies


ADVERTISEMENT

Help Needed In Join Query

Mar 25, 2008

hi,

this is my db tables:

groupallocation
groupid(primarykey)
groupname

systemallocation

systemid(primarykey)
systemname

deviceallocation

deviceid(primarykey)
devicename
sensorallocation

sensorid(primarykey)
sensorname
groupid(foreignkey)
systemid(foreignkey)
deviceid(foreignkey)

so i want to make a query in sensorallocation table should display as like folllows:

i want to make query to join the tables and display the following fields.

sensorid,sensorname,groupname,systemname,devicename

becos in sensorallocation table i do have only groupid,systemid,deviceid only but while displaying i need to display groupname,systemname,devicename

View 3 Replies View Related

Query Help Needed (JOIN)

Jul 20, 2005

I have two tables populated during the use of an application to loguser events and application states. They are named "EventTable" and"StateTable" and the structures follow:EventTable:ID EventTimeStep EventID-- ------------- ---------1 5 E12 22 E23 56 E3StateTableID StateTimeStep StateID-- ------------- -------1 1 S12 39 S2I want to perform a query that reports the StateID of the applicationat the time that each event was logged to the EventTable. The desiredoutput is:ID TimeStep EventID StateID-- -------- ------- -------1 5 E1 S12 22 E2 S13 56 E3 S2I have tried to create a query with an INNER JOIN where the value forthe StateID output field comes from the last row in the StateTableWHERE StateTable.TimeStep <= EventTable.TimeStep and where I use aGROUP_BY EventTable.ID to merge the following rows from the join:3 56 E3 S13 56 E3 S2However, the closest I can get is a query that gives me the wrongstate when applying the GROUP BY clause3 56 E3 S1I also think that the queries I have written is slow and inefficient.Is there a better way to perform this query or is my database designfatally flawed?Thanks,Adam Nemitoff

View 2 Replies View Related

SQL Query JOIN Needed? Too Advanced For Me

Sep 5, 2006

THIS LOOKS LIKE A LOT BUT I JUST WANTED TO GIVE ALL INFORMATION NEEDED FOR YOU TO EASILY ASSIST ME.  I am not good with SQL so please bare with me. I will give a dumbed down table for us to work with:timestamp          -   DATA1 - DATA2 - MAXVALUENEEDED - DATA32006/8/12 12:00       123         125             1289                      121 2006/8/12 12:05       124         128             1291                      1232006/8/15 12:00        130        128              1190                     1242006/8/15 1:00          131        127             1196                      123  The columns labeled DATA do not really matter.  The only important ones are timestamp and MAXVALUENEEDED but I do need the query to return all columns. What the query has to do: The query needs to find the MAX of MAXVALUENEEDED for a given DAY.  Example Output- 2006/8/12      124   128   1291   1232006/8/15      131   127   1196   123As you can see the MAX values were grabbed for each given day and the unique records were returned on a per day basis. My current SQL Query is:  SELECT CONVERT(varchar, timestamp, 101) AS Time, CONVERT(int,LV50AEPM_AMPS_A_VAL0) AS AMPS_A, CONVERT(int,LV50AEPM_AMPS_B_VAL0) AS AMPS_B, CONVERT(int,LV50AEPM_AMPS_C_VAL0) AS AMPS_C,
CONVERT(int,LV50AEPM_KVA_TOT_VAL0) AS KVA_TOTAL, CONVERT(int,LV50AEPM_KW_TOT_VAL0), CONVERT(int,LV50AEPM_VLL_CA_VAL0), CONVERT(int,LV50AEPM_VLL_BC_VAL0), CONVERT(int,LV50AEPM_VLL_AB_VAL0)
FROM Table_1 T1
WHERE CONVERT(int,T1.LV50AEPM_KVA_TOT_VAL0) = (SELECT MAX(CONVERT(int,T2.LV50AEPM_KVA_TOT_VAL0)) FROM Table_1 T2 WHERE CONVERT(varchar,T1.timestamp,101) = T2.timestamp)
ORDER BY Time ASC The problem is it only returns the max value for one day instead of all days.  Can anyone help me correct this?  Thanks in advance for your help. 

View 34 Replies View Related

Urgent: Help Regarding Query To Update Dates In Related Tables

May 28, 2007

I am really stuck here,
I hope to get some helpful answers on this forum.

Ok, I have three four tables in my db,
1- Stages
2- Activities
3- Tasks
4- Subtasks
Structure is like:
Stages
1- SrNo (Unique)
2- Stage
3- StartDate
4- FinishDate


Activities
1- SrNo (Unique)
2- Activity
3- StartDate
4- FinishDate
5- SrNo1 ((FK) from Stages Table)

Tasks
1- SrNo (Unique)
2- Task
3- StartDate
4- FinishDate
5- SrNo1 ((FK) from Activities Table)

Subtasks
1- SrNo (Unique)
2- Subtasks
3- StartDate
4- FinishDate
5- SrNo1 ((FK) from Task Table)

Now what i want is to update Tasks, StartDate and FinishDate according the Min(StartDate) and Max(FinishDate) of related Subtasks and same for Activities and Stages.
I have tried following query to Update tasks, StartDate and FinishDate

Update Tasks Set Tasks.StartDate=(Select Min(Subtasks.StartDate) from Subtasks,Tasks where Tasks.SrNo=Subtasks.SrNo1) from Subtasks,Tasks where Tasks.SrNo=Subtasks.SrNo1

But this query updates all Tasks with Min and Max date from Subtasks regardless of their relation.

Any help, would be appreciated.
Thanks

View 3 Replies View Related

Sql Query String In VS2005 Help Needed. Involves AVG, 2 Tables, And URL Querystrings!

Jan 25, 2008

hey everyone,I'm having trouble cranking out an appropriate SQL query for what I'm trying to do. I'm trying to add a ratings system into a website, I have 2 relevant tables.Files = table listing all uploaded filesRatings = table listing all ratings for filesThe two DB's are theoretically linked by the fact that the ratings table has a field for "fileID" which matches up to "fileID" in the files table. The way the page works, is that there is a querystring in the URL "filename" where "filename" is a field within the files table. So basically I'm looking for the AVG rating.ratings, where rating.fileID = files.fileID, and the appropriate files.fileID is gained from files.fileID WHERE files.filename = request.querystring["filename"]holy crap, i hope that made sense to someone here. i'm not great at explaining this. My problem is I want the AVG ratings.rating from the table ratings.... where ratings.fileID = files.fildIDWhat I have so far, that works except for the AVG part is below. This code will pull only the ratings for the appropriate file, the problem is whenever I try to add "AVG(something)" to it, the query fails.SELECT        files.FID AS Expr1, files.filename, ratings.FID, ratings.ratingFROM            files INNER JOIN                         ratings ON files.FID = ratings.FIDWHERE        (files.filename = @filename) @filename value is gained from the URL querystringany ideas? 

View 1 Replies View Related

Join Query With Three Tables

Aug 30, 2013

I need to make a query to extract data from three tables.The tables are:

Customer

CREATE TABLE [Customer] (
[CustomerCode] VARCHAR(20) PRIMARY KEY NULL,
[CustomerName] VARCHAR(60) NULL,
[CustomerNif] VARCHAR(10) NULL,

[code]....

I wrote this SQL Query based in several tutorial on the net:

"SELECT c.CustomerName, sh.IncidentDesc, sh.IncidentTechInCharge, sih.IncidentChangeTo, sih.IncidentChangeDate FROM Customer c INNER JOIN SupportHistory sh ON c.CustomerCode = 'sh.IncidentCustomerCode' INNER JOIN SupportIncidentHistory sih ON sh.IncidentID = sih.IncidentID"

but it does not return any results.

View 5 Replies View Related

Query To Join 3 Tables

Nov 15, 2013

I have 2 tables:

Element(Element_Id, Element_Name) and Parent_Child(Parent_Id, Child_Id). Parent_Id and Child Id are actually the element Ids only. An element can have more than 1 parent or more than one child.

Now i want the output like this:

Element_Id Element_Name Parent_Name Child_Name

View 3 Replies View Related

3 Tables Join Query Provlem

Oct 26, 2004

Hi

I had a problem in my query and i expalined in detail in the following link


http://www.balainfo.com/forums/viewtopic.php?t=39

View 2 Replies View Related

Query That Join Two Tables And Retrieve A Sum

Jan 13, 2012

I want to join two tables of information together. I want to bring the order information together with the order charge. But since the OrderCharges table can have multiple values, I just want to retrieve the sum of those charges for a specific OrderID+ItemID.

My data looks something like this:

CREATE TABLE #OrderItems
(
OrderItemsID INT IDENTITY (1,1) PRIMARY KEY,
OrderID INT,
ItemID INT
)
SET IDENTITY_INSERT #OrderItems ON

[Code] ....

So I'm looking to see a result set that would like this this:

OrderItemsID-----ItemID-----OrderID----OrderDescription--OrderCharge
----1------------124---------1------------Shipping----------6.55
----2------------156---------1------------Shipping---------16.85
----3------------156---------2------------Shipping----------7.40
----4------------158---------1------------Shipping----------7.85
----5------------158---------2------------Shipping---------15.25

View 2 Replies View Related

Sql Data Join Related Problem

Apr 1, 2008

I am using join for 2 tables in one sql data file.
now i want to build relationship between 2 tables of different SQL file is it possible?
 
 

View 5 Replies View Related

Sql Query Which Uses Multiple Tables But No Common Field To Join

Jan 29, 2004

Hello-

I have a sql query that I am using to populate a datagrid. The problem is one of the tables is a month table. and the other tables are full of data. So there is no common column name to match using a inner join "on".

How do i do this?

View 6 Replies View Related

Performance Related Doubt On The Following Items --&&> LEFT/INNER JOIN Vs IN And Cost Of CONVERT

May 28, 2008

Hi,

1.
Right now in my queries I am using lots of LEFT Joins and INNER JOINs... and I was suggested to look at 'IN'... But with IN I did face some performance issues previously and stopped using it... but I have got new doubts on which query will give me better performance...

A query using LEFTJoin or a query using IN/NOT-IN


2.
This question is about CONVERT...

I have a stored proc which is used for updating a table... and multiple columns [of the same table] and corresponding values are sent to the proc [only a subset of the columns might be sent for updates everytime and the columns to update is not fixed for each run of the SP]...

I have to construct a UPDATE String out of it using string concatenation to finally be able to use "sys.sp_executesql" on that update statement...

This results in me having to use CONVERT() lots of times... and one of the columns among them on which I am doing a CONVERT is of the type XML...

So the question is as follows...
a. Is it preferrable to construct a single UPDATE statement string and execute it using "sys.sp_executesql"
b. Or Is it preferrable to give multiple UPDATE statments... i.e. one update statement for each column [Depending on whether that column has to be updated for that run or not]


i.e. The question essentially is:

Does a single update query constructed using lots of CONVERTS [Basically on INT and XML types]
give more performance over using multiple UPDATE statments on the table
Or is it the other way round..

Thanks,
Pratap.

View 5 Replies View Related

Related Tables

Jul 23, 2005

Is it possible to retrieve all tables that a given one is related tovia foreign keys?

View 2 Replies View Related

Inserting Into Related Tables

Mar 24, 2004

Hi all,

I am trying to insert user's input from a web form into the tables. For example,

PURCHASE TABLE(PurchaseID, PurchaseNo, Date, PartID)

PART TABLE(PartID, PartDescription,MachineID)

MACHINE TABLE(MachineID, MachineName)

On the web form I have textboxes for the Purchase No., date and part description, and a drop down list for the machine name. How do I insert them into the different tables?

I've just start learning ASP.NET and I am using Web Matrix for this. The examples I've seen so far only shows how to insert into a single table.

Thanks!

View 2 Replies View Related

Setting Up FTS On Related Tables

Sep 12, 2005

I have 2 related tables I want to include in a single full text search. How would I go about setting this up?

View 1 Replies View Related

Select 2 Related Tables

May 25, 2006

hi this is probably a dumb question with an easy answer but does anyone know how to do this...

2 tables, one is a supplier list (id, supplier_name) and the other is an order list (id, order_name, supplier_id... etc)

basically i need to join the 2 tables together (id=supplier_id) but i need to display the results without the supplier_id and the supplier table id, only the supplier name?

do i have select only the specific fields I want? or can I exclude the supplier_id and the id from the supplier table?

View 10 Replies View Related

Joining Not Related Tables

Mar 6, 2007

Hi all. how could i join unrelated tables?
for example:
table1: employee
dcno name address telno
1 sarah philippines 111
2 john india 222
3 joy usa 333

table2: hospital
hospname location owner
hosp1 loc1 billgates
hosp2 loc2 ann
hosp3 loc3 love
hosp4 loc4 vic

table3: student
studname load
kim 10

Is it possible to join unrelated tables?

Thanks
-Ron-

View 17 Replies View Related

Indexes On Related Tables...

Jun 17, 2007

Hi,

I have 2 tables with this design: one has ArticleID as primary key and multiple other fields and one has GroupID as primary key and multiple other fields. Each article can belong in multiple groups so I created a new table called articleGroups with only 2 fields: ArticleID and GroupID to show the groups associated with each article. There is a relation between this table and each of the main 2 tables. My question is, in the articleGroup table, does it make any sense to create an Index on ArticleID, GroupID or both? Since the group is needed for each article the Groups will always be queried everytime the article is queried. So, I am not sure if an index is needed?

Thank you,


Regards,

Iulian

View 5 Replies View Related

Select All From Two Many-to-many Related Tables

Oct 11, 2007

Hello, everyone!

Please give your ideas about how to create a query from two tables, which have many-to-many relationship. For example, we have table Book and table Author and consider, that one author had wroten several books and one book had being wroten by several authors. So we have many-to-many relationship of these two tables.
Usually this sutuation resolves by maens of creating the third table AuthorBook, which consist of key fields from the Author table and key fields from the Book table. So that the Author table is the parent table to AuthorBook, and the Book table is the parent table to AuthorBook. So we have two relations one-to-many. Now the question is how to get all related values from both tables, using JOIN operation and the conjunctive table?

I would greatly appreciate any answers

View 9 Replies View Related

INSERING DATA INTO RELATED TABLES

Nov 14, 2007

I have a relationship database that contains two related tables.  Table1 has the fields Customer_Name, Customer_ID, and products_Purchased. Table2 has the fields Customer_Name and Cutomer_ID. I would like to add a new row to Table1for a new purchase by a cutomer. When I try to add a new value in Table1 I get an error message saying I can't add a value to table1 because it requires a corresponding value in Table2. I am using the following code: '**********************************************
("INSERT INTO [Table1]([products_Purchased], [Customer_ID]) VALUES('" & textBox..Text & "',"
& session("ID") & ")"
 ' *****************************************
How do I write an INSERT STATEMENT that adds vaules to both tables, so that the code works?
Any HELP would be appreciated.
charlie

View 3 Replies View Related

Retrieve Data From 3 Tables Which Are Related To Each Other

May 28, 2007

Hey,

I want retrieve data from 3 table my tables structure is this

tblUsers

U_ID - Name

3 John


tblGroups

G_ID - Name

5 Admins
6 Moderators


Now I want join some of the users to different groups for example John maby is a member of two groups (Admins and Moderators)

in order to do this I created a new table names tblGroupsUsers

tblGroupsUsers

ID - User_ID - Group_ID

1 3 5
1 3 6


its ok, but Now I don't know how to retrive my users list from database I don't know how to write a wuery for this
I have tried this :



strSQL = "SELECT tblUsers.name, tblUsers.U_ID, tblGroups.G_ID, tblGroupsUsers.Group_ID, tblGroupsUsers.User_ID FROM tblUsers INNER JOIN tblGroupsUsers ON tblGroupsUsers.User_ID = tblUsers.U_ID, tblGroups WHERE tblGroupsUsers.Group_ID = tblGroups.G_ID ORDER BY tblUsers.name ASC;"



Its working withut error but the problem is the results its like this


John

John


its will retrive the username twice , I think its reading based on tblGroupsUsers table because it has two rows ,
help please I need this how can I configure my query to get eache name once

Thanks

View 8 Replies View Related

Insert Data Into Related Tables

Mar 2, 2008

i am using ms sql server 2005 express for the following:

T1 = {t1.c1(PK), t1.c2, t2.c1(FK)}

T2 = {t2.c1(PK), t2.c2}

where T1 and T2 are tables from the same database, and tn.cn are CoulmnN of TableN
T1 and T2 are linked by the relationship t2.c1

i need to know how to add records to T1 and T2 using ms sql.

record for T2 needs to be added first then retreive t2.c1 from T2 to add record to T1 with t1.c1, t1.c2 t2.c1

please help, thanks

View 2 Replies View Related

Import Excel Into 2 Related Tables

Jan 29, 2014

I have 1 Excel spreadsheet. It has about 50 fields. I need to import this into my Database.The problem is; there are 2 tables that I need to import this into. These 2 tables are related with [ID].So, I need to split the data from 1 spreadsheet between 2 SQL server table. and keep the records related.

View 4 Replies View Related

Delete Records In Two Related Tables?

Jan 30, 2014

I am trying to delete the records in 2 related tables. The 'child' table has a field called [SETA],

I want to delete all the records in this table that contain the same info, as well all the fields in the parent table that is related to this table. They share the [ID] field as key. This is my code:

Code:
DELETE FROM Student a full outer JOIN Qualification b on a.[ID] =b.[ID] WHERE b.[SETA] = @SETA

View 4 Replies View Related

Table Name Convention For Related Tables

Nov 1, 2007

Hi,

If I have 2 tables:

TableA
aID
aCount

TableB
bID
bCount

And I need to create a 3rd table that will look like:

aID
bID

What should I call this table?

I've seen:

relAB

AXB

Any other naming conventions?

View 7 Replies View Related

How To Insert Records Into Related Tables?

Sep 24, 2007

Hi,
I have 3 tables:
Employees with the fields:idEmployee and employeeName
Roles with the fields:idRole and roleName.
An employee can have one or many roles.
I created the table EmployeeRoles with the fields: id,idEmployee,idRole.
idEmployee and idRole are foreign keys.
I want to insert a new employee into Employees table, but I have to insert idEmployee field into EmployeeRoles table.

How can I do this?
Thanks

View 6 Replies View Related

Find All Tables That A Table Is Related To

Sep 8, 2006

how can i find all the names of tables that a specific table is related to in tsql?

View 3 Replies View Related

Retrieve ALL Related Tables Through TSQL

Apr 30, 2008

Many HUGE Thanks to the person who knows how to do this.

Problem: My goal is to take a single data row (myDataRow) from some table (MyTable) and then retrieve every single associated record throughout the database that is related to that datarow. This requires me to first find out what tables are related to the starting table and then recursively pull all of the associated records until I get all of the records associated. Sounds simple right?

The following code only pulls back only those tables that have a child table
with an associated foreign key (i.e. a 1 -> many):


Select [Name] from sysobjects where xtype='U' and Id in(

select fkeyid from sysforeignkeys where rkeyid=

(Select Id from sysobjects where Name='<TableName>'))

order by name


But this query does not work backwards where I start with a child table
and want to know the parents (i.e. many->1 relationship)

Anybody have a clue how to retrieve these parent related tables when starting with a child table? I know it can be done because SQL Server Management lets you select a table (child OR parent) and retrieve the related table(s).

Thank you for any direction you can suggest!

Best Wishes to All
-Eric

View 6 Replies View Related

Help Needed With A Join

Apr 8, 2008

SELECT * FROM A INNER JOIN
B ON A.AId =
(SELECT B.BId
FROM B
WHERE (B.AId = 4))

I have two tables
Table A has several columns and B has just two columns
B.AId and B.BId.

I will pass B.AId as a parameter and that will return more than one B.BId values. Then I need to create a join where A.AId matches B.BId.

I tried the above SQL but it says subquery can't return more than one value. In my case it must return more than on value.
How can I construct the SQL query.
Please Help.
Thanks

View 3 Replies View Related

Loading Data In SQL Server To Related Tables (how)

Jul 14, 2004

Hi I have a question how to load data to tables linked by Foreign Keys in MSDE/SQL server. Example:
If I have 2 tables linked (by Foreign Key):
One table:

ITEM idITEM NAMEITEM CATEGORY (FK)
1cheese 2

And another:

Category IDCATEGORY NAME
1 household
2 food
3 general

How do I enter the load of data
Do I have to enter it as
1cheese2
or is there some way of entering it as
1cheesefood

TDS wizard does not allow me to transfer to views/querries what I thought would be a normal way as I would enter data to view(relevant to Access's form) and it would update related tables . When I wrote sql to do it it said I can not update my view table as too many tables would be affected(I had lookup tables empty then though)
I am doing it by number using TDS wizard to transfer it directly to the main table but there must be a better way

View 1 Replies View Related

Insert Stored Procedure For Related Tables

Feb 24, 2005

I have two sets of related tables: Quote - QuoteDetail and Order - OrderItem

I need to copy Quote - QuoteDetail records to Order - OrderItem tables

I have the stored procedure up to this point: Insert a Quote in the Order table and get the new Order @@Identity.

I need to insert the QuoteDetail records into the OrderItem table using the new OrderID

Thank you for your help.

View 4 Replies View Related

INSERTING MULTIPLE RELATED TABLES IN A TRANSACTION

Jun 2, 2005

I have a problem there must be an answer to, but I cannot find it anywhere on Google.I have a SQL INSERT statement in an ASP.Net page that  inserts into 3 tables in one transaction.The problem is that 2 of the 3 tables are children of the main table, and I need to get the Parent table's Primary Key [which of course has not been inserted yet] to insert into the Child tables.How do I do this?THanks.Doug

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved