SQL Statement - Where Not Joined

Aug 3, 2006

Help.

I have a table with a composite key (two primary keys) that is a foreign key to another table. I need to select all records in the primary key table where there are no matches in the foreign key table... I have no idea how to do this..

Here is how to join the tables:

Select A.Key1, A.Key2 From PrimaryKeyTable A, ForiegnKeyTable B Where A.Key1 = B.Key1 and A.Key2 = B.Key2

I need to query all records that do not join, so basically the inverse of this query. How do I do this? Please let me know if this is in the wrong forum or you need any clarifcation.

Just FYI, on a single Primary key column I would just simply do the following:

Select A.Key From PrimaryTable A, ForiegnTable B Where A.Key not in ( Select A.Key From PrimaryTable A, ForignTable B Where A.Key = B.Key)

but how to with a composite key?

View 4 Replies


ADVERTISEMENT

SELECT Statement Listing Joined Records

Jan 18, 2005

I've searched high and low for info on how to do this... If anyone has an idea, I'd really appreciate it.

I have three tables: PEOPLE, PROJECTS, COMMENTS. I want users from the PEOPLE table to retrieve a list of PROJECTS and be able to add/edit COMMENTS on those projects.

The tables look like:

PEOPLE
people_id (primary key)
first_name
last_name

PROJECTS
projects_id (primary key)
project_title
project_summary

COMMENTS
comments_id (primary key)
projects_id (foreign key)
people_id (foreign key)
comment_detail

I'd like to be able to output something like what I have below, but I don't know how to loop over the comments/people within the select statement for the projects.

DESIRED OUTPUT

Project #1
Comment #1 by Person #1
Comment #2 by Person #3
Comment #3 by Person #8

Project #2
Comment #1 by Person #2
Comment #2 by Person #3
Comment #3 by Person #6

Etc...

I've done it before by just listing the projects and then providing a detail page with all the comments, but it's much less confusing to access all the comments from the same page, grouped by project.

Thanks in advance.

View 1 Replies View Related

Update On Joined Field

Jun 6, 2006

Is it possible to update the filed used in the inner join
 
Update t1 set t1.name=t2.name2
From t1 inner join t2 on t1.name = t2.name
 

View 1 Replies View Related

Joining Two Joined Tables

May 15, 2002

Hi all -

Heres the deal,

I have six tables that are loosly related,

four in one join, two in the other....

in the first join there is a column called commentID -
and is based on a join of the four tables, the results of the
query is based on a where clause

and this needs to be tied into the second set of joined
tables (they are joined on a commentID themselves)

I have both the queries and joins working -

The primary query (4 joined tables) needs to do a lookup on the second (2 joined tables) and add its selected value, into the final result set....



thanks a million for the help!!

take care
tony

View 1 Replies View Related

Delete From Joined Table

Dec 20, 2006

How do I delete from a joined table....

I want to delete all the records from transaction AND order table where status is > 4

sumfing like:


DELETE ORDERS.*, TRANSACTIONS.*
from ORDERS
INNER JOIN TRANSACTIONS
where ORDERS.order_no = TRANSACTIONS.order_no
and status > 4

but doesnt seem 2 like dat???

THANKS :)

View 5 Replies View Related

Update Joined View

Aug 15, 2014

I create a view with 2 joined tables:

with cte as (
select
DataID,
Name,
SubType,
FileType,
MimeType,
VersionID,
Version

from dtree A1, dversdata A2
where A1.dataid=A2.Docid And A1.Subtype='144'
AND
A2.mimetype='application/news-message-id'
update cte set MimeType = 'application/x-outlook-msg', Subtype=749

what I want to do is to update two columns. Both are from different tables and I get an error..

View 1 Replies View Related

When To Use A Joined Table For Comments?

Nov 9, 2005

I have a table with almost a million rows, although it's quite slim with just ID, date, userID, JobID etc.

Now I want to the ability to add comments to some (probably less than 1%) of those lines.

The question is whether to create a separate comments table to join to it, or to create a comments field within the existing table? The comments field would obviously default to NULL, so wouldn't bloat the table unnecessarily if I add that field (right?), and would always be selected with the row from that table, so I'm leaning towards the latter alternative.

Any thoughts, words of warning?

Thanks
Mark

View 17 Replies View Related

Problem With Joined Tables

Feb 1, 2008

I posted Wednesday thinking a SELECT Distinct would solve my problem but it didn't. I have a stored procedure that is used to grab data from 4 tables that I need to join.
The 1st table (Application) holds a job applicant's name and some other data
The 2nd table (Jobs) holds the Job name and test type
The 3rd table (Locations) holds the locations
Then there is a foreign key many to many table (Application_Locations) that holds the applicants UserID and a LocationID. This table may have multiple rows for the same applicant with different locations in each row.

When the procedure is ran I want all the data that I am requesting from the Application table, and all the data that I am requesting from the Jobs table but only the 1st returned result of the Join on the Locations and Application_Locations table. What do I need to do to correct this so that I only display 1 row for each UserID no matter how many locations thay may have applied to. (You will notice that there are some IF statements so only the 2nd and 4th queries in the sproc are the ones that apply )

Here is the SPROC that is currently in place but is displaying a row for each location.


CREATE PROCEDURE sp_AdminListApplicants

@LocationID int,
@FolderID smallint,
@JobID int,
@SortOrder char(1)

AS


IF @JobID <> 9999
BEGIN
IF @LocationID <> 9999
BEGIN
SELECT
A.UserID,
A.Completed,
A.FolderID,
A.AppDateTimeStart,
A.ResumeFileName,
A.FirstName,
A.LastName,
A.PrescreenScore,
A.JobID,
A.ViewPre,
A.ViewApp,
A.ViewReport,
A.ViewResume,
J.JobTitle,
J.TestType,
L.BranchAbbreviation,
AL.LocationID
FROM
Locations L
INNER JOIN Application_Locations AL ON AL.LocationID = L.LocationID
INNER JOIN Application A ON AL.UserID = A.UserID
INNER JOIN Jobs J ON J.JobID = A.JobID
WHERE
AL.LocationID= @LocationID
AND A.FolderID= @FolderID
AND A.JobID = @JobID
ORDER BY
CASE
WHEN @SortOrder = '4' THEN A.AppDateTimeStart
END DESC,
CASE
WHEN @SortOrder = '6' THEN A.PreScreenScore
END DESC,
CASE
WHEN @SortOrder = '2' THEN A.LastName
END DESC,
CASE
WHEN @SortOrder = '5' THEN A.PreScreenScore
END ASC,
CASE
WHEN @SortOrder = '3' THEN A.AppDateTimeStart
END ASC,
CASE
WHEN @SortOrder = '1' THEN A.LastName
END ASC
END

ELSE
BEGIN
SELECT
A.UserID,
A.Completed,
A.FolderID,
A.AppDateTimeStart,
A.ResumeFileName,
A.FirstName,
A.LastName,
A.PrescreenScore,
A.JobID,
A.ViewPre,
A.ViewApp,
A.ViewReport,
A.ViewResume,
J.JobTitle,
J.TestType,
L.BranchAbbreviation,
AL.LocationID
FROM
Locations L
INNER JOIN Application_Locations AL ON AL.LocationID = L.LocationID
INNER JOIN Application A ON AL.UserID = A.UserID
INNER JOIN Jobs J ON J.JobID = A.JobID
WHERE
A.FolderID= @FolderID
AND A.JobID = @JobID
ORDER BY
CASE
WHEN @SortOrder = '4' THEN A.AppDateTimeStart
END DESC,
CASE
WHEN @SortOrder = '6' THEN A.PreScreenScore
END DESC,
CASE
WHEN @SortOrder = '2' THEN A.LastName
END DESC,
CASE
WHEN @SortOrder = '5' THEN A.PreScreenScore
END ASC,
CASE
WHEN @SortOrder = '3' THEN A.AppDateTimeStart
END ASC,
CASE
WHEN @SortOrder = '1' THEN A.LastName
END ASC
END
END

ELSE
BEGIN
IF @LocationID <> 9999
BEGIN
SELECT
A.UserID,
A.Completed,
A.FolderID,
A.AppDateTimeStart,
A.ResumeFileName,
A.FirstName,
A.LastName,
A.PrescreenScore,
A.JobID,
A.ViewPre,
A.ViewApp,
A.ViewReport,
A.ViewResume,
J.JobTitle,
J.TestType,
L.BranchAbbreviation,
AL.LocationID
FROM
Locations L
INNER JOIN Application_Locations AL ON AL.LocationID = L.LocationID
INNER JOIN Application A ON AL.UserID = A.UserID
INNER JOIN Jobs J ON J.JobID = A.JobID
WHERE
AL.LocationID= @LocationID
AND A.FolderID= @FolderID
ORDER BY
CASE
WHEN @SortOrder = '4' THEN A.AppDateTimeStart
END DESC,
CASE
WHEN @SortOrder = '6' THEN A.PreScreenScore
END DESC,
CASE
WHEN @SortOrder = '2' THEN A.LastName
END DESC,
CASE
WHEN @SortOrder = '5' THEN A.PreScreenScore
END ASC,
CASE
WHEN @SortOrder = '3' THEN A.AppDateTimeStart
END ASC,
CASE
WHEN @SortOrder = '1' THEN A.LastName
END ASC
END

ELSE
BEGIN
SELECT
A.UserID,
A.Completed,
A.FolderID,
A.AppDateTimeStart,
A.ResumeFileName,
A.FirstName,
A.LastName,
A.PrescreenScore,
A.JobID,
A.ViewPre,
A.ViewApp,
A.ViewReport,
A.ViewResume,
J.JobTitle,
J.TestType,
L.BranchAbbreviation,
AL.LocationID
FROM
Locations L
INNER JOIN Application_Locations AL ON AL.LocationID = L.LocationID
INNER JOIN Application A ON AL.UserID = A.UserID
INNER JOIN Jobs J ON J.JobID = A.JobID
WHERE
A.FolderID= @FolderID
ORDER BY
CASE
WHEN @SortOrder = '4' THEN A.AppDateTimeStart
END DESC,
CASE
WHEN @SortOrder = '6' THEN A.PreScreenScore
END DESC,
CASE
WHEN @SortOrder = '2' THEN A.LastName
END DESC,
CASE
WHEN @SortOrder = '5' THEN A.PreScreenScore
END ASC,
CASE
WHEN @SortOrder = '3' THEN A.AppDateTimeStart
END ASC,
CASE
WHEN @SortOrder = '1' THEN A.LastName
END ASC
END
END
GO




Miranda

View 5 Replies View Related

Behavior Of SQL On Joined Queries

Jul 20, 2005

Hi all,Currently our product has a setup that stores information abouttransactions in a transaction table. Additionally, certain transactionspertain to specific people, and extra information is stored in anothertable. So for good or ill, things look like this right now:create table TransactionHistory (TrnID int identity (1,1),TrnDT datetime,--other information about a basic transaction goes here.--All transactions have this infoPrimary Key Clustered (TrnID))Create Index TrnDTIndex on TransactionHistory(TrnDT)create table PersonTransactionHistory (TrnID int,PersonID int,--extended data pertaining only to "person" transactions goes--here. only Person transactions have thisPrimary Key Clustered(TrnID),Foreign Key (TrnID) references TransactionHistory (TrnID))Create Index TrnPersonIDIndex on PersonTransactionHistory(Person)A query about a group of people over a certain date range might fetchinformation like so:select * from TransactionHistory THinner join PersonTransactionHistory PTHon TH.TrnID = PTH.TrnIDwhere PTH.PersonID in some criteriaand TH.TrnDT between some date and some dateIn my experience, this poses a real problem when trying to run queriesthat uses both date and personID criteria. If my guesses are correct thisis because SQL is forced to do one of two things:1 - Use TrnPersonIDIndex to find all transactions which match the personcriteria, then for each do a lookup in the PersonTransactionHistory tofetch the TrnID and subsequently do a lookup of the TrnID in the clusteredindex of the TransactionHistory Table, and finally determine if a giventransaction also matches the date time criteria.2 - Use TrnDTIndex to final all transaction matching the date criteria,and then perform lookups similar to the above, except for personID insteadof datetime.Compounding this is my suspicion (based on performance comparison of whenI specify which indexes to use in the query vs when I let SQL Serverdecide itself) that SQL sometimes chooses a very non optimal course. (Ofcourse, sometimes it chooses a better course than me - the point is I wantit to always be able to pick a good enough course such that I don't haveto bother specifying). Perhaps the table layout is making it difficult forSQL Server to find a good query plan in all cases.Basically I'm trying to determine ways to improve our table design here tomake reporting easier, as this gets painful when running report forlarge groups of people during large date ranges. I see a few options basedon my above hypothesis, and am looking for comments and/or corrections.1 - Add the TrnDT column to the PersonTransactionHistory Table aswell. Then create a foreign key relationship of PersonTransactionHistory(TrnID, TrnDT) references TransactionHistory (TrnID, TrnDT) and createindexes on PersonTransactionHistory with (TrnDT, PersonID) and(PersonID, TrnDT). This seems like it would let SQL Server makemuch more efficient execution plans. However, I am unsure if SQL servercan leverage the FK on TrnDT to use those new indexes if I give it a querylike:select * from TransactionHistory THinner join PersonTransactionHistory PTHon TH.TrnID = PTH.TrnIDwhere PTH.PersonID in some criteriaand TH.TrnDT between some date and some dateThe trick being that SQL server would know that it can use PTH.TrnDT andTH.TrnDT interchangably because of the foreign key (this would support allthe preexisting existing queries that explicitly named TH.TrnDT - any thatdidn't explicitly specify the table would now have ambigious columnnames...)2 - Just coalesce the two tables into one. The original intent was to savespace by not requiring extra columns about Persons for all rows, many ofwhich did not have anything to do with a particular person (for instance acontact point going active). In my experience with our product, the enduser's decisions about archiving and purging have a much bigger impactthan this, so in my opinion efficient querying is more important thanspace. However I'm not sure if this is an elegant solution either. It alsomight require more changes to existing code, although the use of viewsmight help.We also run reports based on other criteria (columns I replaced withcomments above) but none of them are as problematic as the situationabove. However, it seems that if I can understand the best way to solvethis, I will be able to leverage that approach if other types of reportsbecome problematic.Any opinions would be greatly appreciated. Also any references to goodsources regarding table and index design would be helpful as well (onlineor offline references...)thanks,Dave

View 3 Replies View Related

Have Been Down For Two Days Now Because We Joined A Domain And Now This...

Apr 3, 2008

Two days of downtime does not make a happy DBA.

In our frustration we dropped database "Search" completely as restoring it from backup was giving us other authorization errors. Fortunately we could rebuild the searches on the fly.

So now our service broker activation procedure tells us:

04/03/2008 17:49:51,spid55s,Unknown,The activated proc [dbo].[MessageProcessor_NameChange] running on queue AMG_Search.dbo.NameChangeQueue output the following: 'The database owner SID recorded in the master database differs from the database owner SID recorded in database 'Search'. You should correct this situation by resetting the owner of database 'Search' using the ALTER AUTHORIZATION statement.'

My username created the database. I am dbo. So what exactly am I supposed to change the owner to?

I try this:


ALTER AUTHORIZATION ON DATABASE::[Search] TO MySelf

Where MySelf is my username. And I am told Msg 15110, Level 16, State 1, "The proposed new database owner is already a user or aliased in the database" So what the heck we'll make SA the owner.

And that works.

I DON'T GET THIS PEOPLE. I created the database I am not allowed to own it anymore? We formatted the server. We reinstalled SQL server from scratch. We recreated all the usernames. Was our mistake restoring the old data from backup? Was I supposed to re-run the DDL and key all the data back in again? Is that the reccomended restore procedure? The users will be thrilled to hear this :-)

My days as an Oracle DBA were nothing like this. Security was just not this troublesome...

So if someone older, wiser, and with more experience would explain the above error message and how it occurs I would appreciate it, because something tells me I'm going to be stuck in this place again...





View 7 Replies View Related

Joined View Does Not Contain All Colums

Jul 20, 2006

The joined view is named "dbo.viewExecView" and is like:

SELECT Bank_No, data_center
FROM [ALPHASQL2000].ev_db.dbo.Bank

The new view that joins to the above view is like:

SELECT bank.BankID, evBank.data_center AS DataCenterID
FROM dbo.Bank AS bank INNER JOIN
dbo.viewExecView_Bank AS evBank ON bank.BankID = evBank.BankID WHERE (bank.InactiveDate IS NULL)

Note: The data_center column (an int) was recently added to the Bank table in the linked ev_db database and it shows up there. It also shows up in the view "dbo.viewExecView". It does not appear in the new view that joins to "dbo.viewExecView". And when I run the 'new' view, I get an Error Message: Invalid column name 'data_center'.

I've tried to simplify this as much as possible while still including the pertinent information. Any help very much appreciated, I am currently stumped.

Regards,

Joe

View 4 Replies View Related

How To Specify A Row Filter On Joined Tables

Dec 7, 2006

I am using SQL Server 2005 to publish joined tables for SQL Mobile subscribers for merge replication and column level tracking.

Using Management Studio I am trying to join tables and specify row filters on the joined tables. I.E. table 1 is joined with table 2. I need to define row filters for table 1 and row filters specific to table 2.

An example would be: Table 1 is a customer table that I filter on a specific customer. Table 2 might be an orders table that I need to join to get the customers orders but I also want to filter for open orders only.

When I specify the row filter for table 2 the join appears to be ignored and I receive the complete table 2 with the row filter applied.

I have searched the online books and the web and I have not run accross an example of using both joins and row filters where the filters are specified for both joined tables.

Is this possible via the Management Studio?

Thanks,

Ron

View 4 Replies View Related

Joined Table -- Display In Datagrid

Apr 20, 2007

Ok here goes.  I have 3 tables, one holds case info, the 2nd holds possible outcome on the charges, and they're joined on a 3rd table (CaseOutComes).  With me so far?  Easy stuff, now for the hard part.
Since there's a very common possiblitly that the Case has multiple charges, we need to track those, and therefore, display them on a datagrid or some other control.  I want the user to be able to edit the info and have X number of dropdowns pertaining to how many ever charges are on the case.  I can get the query to return the rows no sweat, but ...merging them into 1 record (1 row) with mutiple drops is seeming impossible -- I thought about using a placeholder and added the controls that way, but it was not in agreement with what I was trying to tell it .
Any ideas on how to attack this?

View 3 Replies View Related

Syntax Error With Joined Update

Mar 24, 2008

Hello all,
 Iv been making a lot of progress on my first functional webapp, but I cannot get this bit of code to work correctly.  I think my UPDATE SQL statement is where the problem is.  It works fine the first time through when there is no Session("estimateid") set, but after that is set it gives me error this on line 40:
Incorrect syntax near '('.
 1 Dim CustID As Integer
2
3 Dim DbConnection As SqlConnection
4 DbConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("harringtonairdb").ConnectionString)
5 DbConnection.Open()
6 Dim DbCommand As SqlCommand
7
8 If Session("estimateid") = 0 Then
9 Dim DbSqlInsert As String
10 DbSqlInsert = "INSERT INTO tblcustomers (strname, strAddress1, strAddress2, strCity, strState, strZip, strPhone, strEmail, strContact) VALUES (@name, @address1, @address2, @city, @state, @zip, @phone, @email, @contact)" & "SELECT @@IDENTITY AS CustID"
11 DbCommand = New SqlCommand(DbSqlInsert, DbConnection)
12 Else
13 Dim DbSqlUpdate As String
14 DbSqlUpdate = "UPDATE tblcustomers SET (strcustname=@name, straddress1=@address1, straddress2=@address2, strcity=@city, strstate=@state, strzip=@zip, strphone=@phone, stremail=@email, strcontact=@contact) JOIN tblestimates ON pkcustomerid WHERE pkestimateid=@estimateid"
15 DbCommand = New SqlCommand(DbSqlUpdate, DbConnection)
16 DbCommand.Parameters.AddWithValue("@estimateid", Session("estimateid"))
17
18 End If
19
20 DbCommand.Parameters.AddWithValue("@name", txtCustName.Text)
21 DbCommand.Parameters.AddWithValue("@address1", txtCustAddress1.Text)
22 DbCommand.Parameters.AddWithValue("@address2", txtCustAddress2.Text)
23 DbCommand.Parameters.AddWithValue("@city", txtCustCity.Text)
24 DbCommand.Parameters.AddWithValue("@state", txtCustState.Text)
25 DbCommand.Parameters.AddWithValue("@zip", txtCustZip.Text)
26 DbCommand.Parameters.AddWithValue("@phone", txtCustPhone.Text)
27 DbCommand.Parameters.AddWithValue("@email", txtCustEmail.Text)
28 DbCommand.Parameters.AddWithValue("@contact", txtCustTimes.Text)
29
30
31 If Session("estimateid") = 0 Then
32 CustID = Convert.ToInt32(DbCommand.ExecuteScalar())
33 DbCommand.Dispose()
34 Dim DbSqlInsert As String
35 DbSqlInsert = "INSERT INTO tblestimates (fkcustomerid) VALUES (@customerid)" & "SELECT @@IDENTITY AS EstimateID"
36 DbCommand = New SqlCommand(DbSqlInsert, DbConnection)
37 DbCommand.Parameters.AddWithValue("@customerid", CustID)
38 Session.Add("estimateid", Convert.ToInt32(DbCommand.ExecuteScalar()))
39 Else
40 DbCommand.ExecuteNonQuery()
41 End If
42
43 DbConnection.Close()
44 DbCommand.Dispose()
 

View 3 Replies View Related

Ordering Of Joined Columns In The FROM Clause

Nov 26, 2001

Bottom line question:
Does it make a difference which table is referenced first following the ON keyword in a FROM clause when creating a join?

--Example 1:
SELECT * FROM TABLE01 t1, JOIN TABLE02 t2
ON t1.ID = t2.ID

--Example 2:
SELECT * FROM TABLE01 t1, JOIN TABLE02 t2
ON t2.ID = t1.ID

Does the sequencing of the tables after the ON keyword make a difference?

Thanks in advance for your help.

View 1 Replies View Related

Slow Query On Joined Tables

Sep 12, 2006

Hi!

I have 4 tables inner joined. Two of tables have ~500,000 rows, while other 2 have ~60,000. There are 4-5 WHERE conditions for 3 tables.
Is it normal that a query lasts ~13-15 seconds? I tried indexing in all ways, subselects, temp tables etc, nothing helped.

I think it is unuseful to use indexes because WHERE conditions apply not to one, but to 3 tables.

Is there anyone who is expert in this topic?
Thanx
B

View 2 Replies View Related

Set-based Update - Table Joined On Itself

Dec 15, 2005

Guys - sorry for the long post - hope it's clear

DDL/DML below

I want to update the startdate column (for all rows) so that when period is 0 then the new value
is a hardcoded value (say '01-Dec-2000') but for all other rows it takes the value in the
enddate column for the row of the previous column (with the same freq)

ie the startdate column for period 1 takes the enddate value for period 0 and so on for a particular freq

create table #periods (period int , startdate datetime , [enddate] datetime , freq int)
insert #periods ( period , startdate , enddate , freq)
select 0 , '01-Jan-1900' , '31-Jan-2001' , 1
union all
select 1 , '01-Jan-1900' , '28-Feb-2001' , 1
union all
select 2 , '01-Jan-1900' , '31-Mar-2001' , 1
union all
select 3 , '01-Jan-1900' , '30-Apr-2001' , 1
union all
select 4 , '01-Jan-1900' , '31-May-2001' , 1
union all
select 0 , '01-Jan-1900' , '31-Jan-2002' , 3
union all
select 1 , '01-Jan-1900' , '28-Feb-2002' , 3
union all
select 2 , '01-Jan-1900' , '31-Mar-2002' , 3
union all
select 3 , '01-Jan-1900' , '30-Apr-2002' , 3
union all
select 4 , '01-Jan-1900' , '31-May-2002' , 3

select * from #periods -- gives

periodstartendfreq
01900-01-01 00:00:00.0002001-01-31 00:00:00.0001
11900-01-01 00:00:00.0002001-02-28 00:00:00.0001
21900-01-01 00:00:00.0002001-03-31 00:00:00.0001
31900-01-01 00:00:00.0002001-04-30 00:00:00.0001
41900-01-01 00:00:00.0002001-05-31 00:00:00.0001
01900-01-01 00:00:00.0002002-01-31 00:00:00.0003
11900-01-01 00:00:00.0002002-02-28 00:00:00.0003
21900-01-01 00:00:00.0002002-03-31 00:00:00.0003
31900-01-01 00:00:00.0002002-04-30 00:00:00.0003
41900-01-01 00:00:00.0002002-05-31 00:00:00.0003



Desired result
select * from #periods -- gives

periodstartendfreq
02000-12-01 00:00:00.0002001-01-31 00:00:00.0001
12001-01-31 00:00:00.0002001-02-28 00:00:00.0001
22001-02-28 00:00:00.0002001-03-31 00:00:00.0001
32001-03-31 00:00:00.0002001-04-30 00:00:00.0001
42001-04-30 00:00:00.0002001-05-31 00:00:00.0001
02000-12-01 00:00:00.0002002-01-31 00:00:00.0003
12002-01-31 00:00:00.0002002-02-28 00:00:00.0003
22002-02-28 00:00:00.0002002-03-31 00:00:00.0003
32002-03-31 00:00:00.0002002-04-30 00:00:00.0003
42002-04-30 00:00:00.0002002-05-31 00:00:00.0003


/*
I know I need a case statement to test for column 0 and to join the table on itself and have put something together
but it fails for column 0 and updates to NULL - I think it must be to do with the join ??

This is what I've got so far :

UPDATE PA1
SET
PA1.Startdate =
CASE
WHEN PA2.period = 0
THEN
2000-12-01 00:00:00.000
ELSE
PA1.Enddate
END
FROM #periods AS PA1
JOIN #periods AS PA2 ON PA1.Freq = PA2.Freq AND PA1.Period = PA2.Period + 1

Any help gratefully received as always
*/

View 5 Replies View Related

Return Values Not In Joined Table

Jul 24, 2012

I'm looking to pull back some results but not include those that have a value in a column that matches a value in a temp table column.

The below code returns all the values rather than excluding those that are in the temp table.

Code:
------Folder Differences-----
--Create Temp Table--
CREATE TABLE #fdiff
(foldername VARCHAR(255))
SELECT
replace(
replace(foldername,'[Template] ','')

[Code] .....

View 2 Replies View Related

Detecting Joined Records That Number Only 1

Oct 1, 2013

I have 2 tables:

Table 1 Customers with column CustomerId
Table 2 Purchases with columns PurchaseId and CustomerId

I want to select all customers who have made just 1 purchase, what would be the sql for that? I know I can join the tables to get the customers with purchases, but I don't know how to limit it to those with just 1 purchase (and exclude all the other customers).

View 9 Replies View Related

T-SQL (SS2K8) :: Get Rows And Sum In Joined Table?

May 2, 2015

I want to return all rows in table giftregistryitems with an additional column that holds the sum of column `amount` in table giftregistrypurchases for the respective item in table giftregistryitems.

What I tried, but what returns NULL for purchasedamount, where I want purchasedamount to be the sum of the `amount` for THAT item, based on giftregistrypurchases.itemid=giftregistryitems.id:

SELECT (SELECT SUM(amount) from giftregistrypurchases gps where registryid=gi.registryid AND gp.itemid=gps.itemid) as purchasedamount,*
FROM giftregistryitems gi
LEFT JOIN giftregistrypurchases gp on gp.registryid=gi.id
WHERE gi.registryid=2

How can I achieve what I need?

Here's my table definition and data:

USE [tt]
GO
/****** Object: Table [dbo].[giftregistry] Script Date: 09-05-15 11:15:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[giftregistry](
[id] [int] IDENTITY(1,1) NOT NULL,

[code]....

Desired results:

purchasedamountidregistryidtitleogimgdescriptionURLamountpricecreatedate

[URL]

View 9 Replies View Related

Get Most Recent Data From Joined Tables??

Apr 25, 2008

Hello, i have this problem
Table1
tbl1
pcb varchar(30)serial varchar(30)result varchar(30)

tbl2:
pcb varchar(30)date_time varchar(30)result varchar(30) data1 varchar(30)data2 varchar(30),


what i need is query the tbl1 for a range of serials,get the pcb and for those pcb's query the tbl2 for data1,data2
The resultSet should be a join on the two tables, Columns {serial} from tbl1 and {pcb,date_time,data1,data2} from tbl2



Please follow my simple example:
Suppose tbl1 has these 2 records
tbl1 = pcb1,sn1,pass
pcb2,sn2,pass
pcb3,sn3,pass

tbl2= pcb1,date1,pass,dataX1,dataY1
pcb1,date2,pass,dataX2,dataY2
pcb2,date3,pass,dataX3,dataY3
pcb3,date4,pass,dataX4,dataY4
pcb1,date5,pass,dataX5,dataY5
pcb2,date6,pass,dataX6,dataY6



where date1 is the most recent date and date6 the least recent

Request:what i want is for serial>=sn1 and serial<=sn2,get the pcbs from tbl1(which are pcb1 and pcb2) and based on these, query the tbl2
for the other data but retrieve only most recent records.

The correct ResultSet should be

pcb1,sn1,date1,dataX1,dataY1
pcb2,sn2,date3,dataX3,dataY3

and not
pcb1,date1,pass,dataX1,dataY1
pcb1,date2,pass,dataX2,dataY2
pcb1,date5,pass,dataX5,dataY5
pcb2,date3,pass,dataX3,dataY3
pcb2,date6,pass,dataX6,dataY6

What i already did is this:


select max(CONVERT(DATETIME,tbl2.date_time,103)),tbl1.serial,tbl2.pcb
from tbl2
left JOIN tbl1
ON tbl2.Pcb=tbl1.pcb
where tbl1.serial>='1' and tbl1.serial<='53'
and tbl2."Result" like 'pass' and tbl1."result" like 'pass'
group by tbl2.pcb,tbl1.serial;


This works correctly for getting serial from tbl1, date_time and pcb from tbl2.But unfortunately i also need data1 and data2 columns from tbl2.
If i include them in the Select Clause i have to include them also in the group by ,and this gives me also duplicate records (by using this OR philosophy).I mean, it would give all records containing (pcb1,pcb2),much like my example


How can i resolve this issue?
Thank you very much

View 1 Replies View Related

Getting An Average From Field Across Joined Tables

Jun 11, 2008

I'm managing an amature online university and I've been charged with creating a deans list. I have a table for exam results for each course.. currently totaling 5. I have an employeeID column and a total_points column in each table. Sooooo I need to join all the tables and get an average for total_points where the employeeID matches across tables. I have no idea how to write this select.. any help?

View 1 Replies View Related

Four Tables Inner Joined - Select Associated Accounts

Feb 14, 2014

I have four tables (all inner joined) and currently they give me the results i need. However, my boss has now asked me to return all associated accounts as well.

I am currently pulling data from the four tables to make up my results table, and the returned results are based on the loan types in my loans tables having a loan type of '1A'

So if the loan type is 1A I get a result.

However, Mr Smith (for example) may have three loans but only one of them is type '1A'. The other two might be type '5H' and '2'.

What I need to be able to do is return all the associated accounts of any customer that has a type '1A' loan.

This is my code:

Select c.customernumber, l.accountsuffix, c.forename, c.surname, lt.code, l.balance, j.journeynumber from customers c
inner join loanagreements l on c.customerid = l.customerid
inner join loantypes lt on l.loantypeid = lt.loantypeid
inner join journeys j on c.journeyid = j.journeyid
Where j.journeynumber = 93
and lt.code = '1a'
and l.balance >0

View 6 Replies View Related

Selecting Only The Last Record In Joined Table

Oct 10, 2005

Hello everyone, I have a query problem.I'll put it like this. There is a 'publishers' table, and there is a'titles' table. Publishers publish titles (of course). Now I want to make aquery (in MS SQL Server) that would return the last title published by everyof the publishers. Quite clear situation. But I can't make it work.If I use inner join (which I should, because I need data from both tables)then I get a result showing all publishers and all titles. What I want toget is all publishers, and only their last title, so I don't have more thanone line for the same publisher, and this line should contain publisherdetails and last title details.I tried using DISTINCT, but it works on a whole resultant row rather then acolumn, and since rows are all distnict (because they also contain columnsfrom titles) this didn't help me.What I can do is (in my application) first get a list of publishers, andthen loop through them selecting only the last title belonging to eachpublisher. I want to see if there is a way to accomplish the same thing withan SQL query (or maybe a stored procedure, view, or whatever). Anything ispossible, as long as it stays within SQL server and doesn't rely on theclient application.Of course, both 'publishers' and 'titles' tables have a primary key('publisherID', and 'titleID'), and 'titles' has a 'publisherID' columnwhich relates titles with publishers.Help :)

View 4 Replies View Related

Help With Blocking On Querying Two Joined Tables

Dec 8, 2005

I get a 90-120 second blocking when send 15 or so simultaneous queriesto SQL Server 2000 that query a view made up of two joined tables.After each query is blocking for the same amount of time they allreturn. Further identical queries of this type work in 3-4 seconds(caching?) until hours later where it happens again. If I query thetables directly (without the view) I still get the same blocking. If Iremove the join (it is a simple inner join on two columns) I do not getthe blocking.Any ideas?

View 3 Replies View Related

Querying Joined Tables With 0 Results

Jan 18, 2006

This seems like a very simple question but i have never been able tofind an easy answer to it.I have a user table and i do a join with another table, we'll call theother table a results table.The results table has numerous rows with the userid foreign key.I want to make a query that will give me the number of rows in theresults table for each user where the result is some valueThe query is simple to make but will only show the users who have arecord in the results table the meet the where criteria, however i wantto display each user and show a record count of 0 when there are noresults in the results table that match the criteria.for example i have 2 tables.tblUsers_______________userid | username--------------------------1 | user12 | user2tblAnswers________________userid | answer----------------------------1 | 11 | 01 | 42 | 12 | 0if i run the query:select max(username), count(answer) from tblUsersleft outer join tblanswers on tblAnswers.userid = tblUSers.idwhere tblAnswers.answer = 4group by tblUsers.idi just getuser1 | 1i want to getuser1 | 1user2 | 0the only way ive found to do this is with a temp table and a curser tocreate all the users records and go back through an insert the answercount for each user. This approach seems very expensive and requires aquery that is 3 times larger than is needed for the same resultswithout including 0 count records. I know there must be a better way todo this.Any help is appreciated.

View 2 Replies View Related

Better Method Than Joined Query Tables

Nov 27, 2007

Hello,

I'm working on a query for a report. I've done this before and it works, but I think it's a little slow due to the joins and I'm wondering if I'm doing this the best way.

This is from a Microsoft CRM system. I'm only using the LEAD table. There is a field on the lead table called StateCode. When a user "Qualifies" a lead, the statecode changes. The report requires a column for total leads, a column for # of leads qualified, and a column for % of leads qualified. There are other columns, but those three will illustrate the problem.

Because total leads means all statecode values are included, and Qualified leads means only one statecode value is included, I can't get those two values from the same query (that I know of). So what I do is take two queries, one for total leads, and one for qualified leads, put them in parenthesis and name them, and then join them on the name of the leadsource, like below. I often end up with 10 or 15 of these "Query Tables" in my main query. Is this the best way?





Code Block
SELECT * FROM
(
SELECT
LeadSource
, COUNT(CreatedOn)
FROM
Leads
GROUP BY
LeadSource
) as A

LEFT OUTER JOIN

(
SELECT
LeadSource
, Count(CreatedOn)
, Count(CreatedOn) / (SELECT COUNT(CreatedOn) FROM leads) AS "% of Leads Qualified from this Lead Source"
FROM
Leads
WHERE
StateCode = 2
GROUP BY
LeadSource
) as B
ON
A.LeadSource = B.LeadSource






Thanks,
Andy

View 3 Replies View Related

How To Update Joined Table Using Instead Of Triggers

Jun 25, 2007

Hi
i have a view that contain multiple tables from my database and i want to view it on datagridview and update it's data
some people says you can update joined tables using instead of triggers
how is that ?is there any example ?

thanks in advance.

View 4 Replies View Related

How To Get Aggregate Column From Joined Table

Feb 6, 2008

Can someone please help me with a better way to format the following query. This works, but I know it is hidious.






Code Snippet

select

convert(varchar, processed, 101) as Date,
count(o.id) as [# Orders],
sum(distinct a.runnercount) as [# Runners],
sum(o.total) as [$ Gross],
sum(o.fee) as [$ Fees],
(sum(o.total)-sum(o.fee)) as [$ Net]

from [order] o join (select convert(varchar,processed,101) as date, count(*) as runnercount from orderitem oi inner join [order] o on o.id = oi.orderid where typeofextraid = 4 group by convert(varchar,processed,101)) a on convert(varchar,processed,101) = a.date

where statemented = @statemented
group by convert(varchar, processed, 101)
2 tables: Order and OrderItem. I need the sum of a specific record type from the OrderItem table along with all the other aggregate columns group by day.

Thanks.

Nathan

View 1 Replies View Related

View With Aggregate Function And Joined Tables

Mar 2, 2007

I have created the following view:
 
Create view vwOrderItemTotal2
AS
SELECT ItemName, fkMenuItemID, Sum(Quantity) as [SumOfMenuITems] FROM OrderItems GROUP BY fkMenuItemId, ItemName
 
When I present my data in a GridView, it works fine.  For example, several orders for milk are returned as a summary quantity of 26 gallons in a single row of the GridView like this:
 
26 Milk
 
Now I need to filter my data by OrderDate and Zipcode.  I created this new view:
 
Create view vwOrderItemTotal5
AS
SELECT Orders.Zipcode, Orders.OrderDate, OrderItems.ItemName, OrderItems.fkMenuItemID, Sum(Quantity) as [SumOfMenuITems]
FROM Orders INNER JOIN OrderItems
ON Orders.OrderID = OrderItems.fkOrderID
GROUP BY fkMenuItemId, ItemName, Zipcode, OrderDate
 
When I present my data in a Gridview using the new view I get a GridView with multiple rows for milk where each order has its own row like this:
 
1 Milk
5 Milk
6 Milk
6 Milk
3 Milk
1 Milk
4 Milk
 
But I want the data presentation in one row for each ItemName (e.g. Milk) as with my first view.  Can I adjust my new view to achieve this, or should I stick with my first view (vwOrderItemTotal2) and adjust the Select Command in my SqlDataSource (hasn’t worked yet). 
I think that what I want is for the returned data to be grouped by fkMenuItemId only, but the sql server admin won’t let me create a view without including the other fields in the Group By clause.  Thanks for any help provided in solving this.
 

View 4 Replies View Related

How Can I Read Type Of All Fields In Joined Query?

Nov 29, 2007

How can I read type of all fields in joined query?
Is there a stored procedure method to use for this purpose?
 
Thanks

View 3 Replies View Related

Placing Joined Tables On Separate Disks

Apr 7, 2008

I've read that if particular tables are frequently queried together through a join then these tables should be placed on different devices on different physical disks.
What does this mean exactly and how would you configure this?
Is this a common practice in high-performance real-world environments (or should it be)?
 

View 3 Replies View Related

How To Update A Row Based On Left-joined Tables?

May 12, 2008

Each row of my datagrid comes from two tables, A and B, which are (left) joined: not every row from table A has a corresponding row in table B. I think this is quite a common scenario.If I want to edit a row in my datagrid which contains data from both Table A and Table B then presumably I can just use an UPDATE statement behind the scenes.But what happens if I want to edit a particular row in the datagrid which contains data from Table A but no corresponding data from table B? I can't use an UPDATE statement because the record in Table B doesn't yet exist. So what do I do?Does anyone know the answer to this, or could you point me to a good tutorial please? 

View 4 Replies View Related







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