Showing posts with label tables. Show all posts
Showing posts with label tables. Show all posts

Friday, March 30, 2012

Query Across Servers

Hi,
Is it possible to execute a query asking for joined data
from different tables on two different servers and
databases?
SQLServer1 SQLServer2
-- --
09.0.0.30\TestData 198.160.30.20\TestData2
I need to run a query against tables in the TestData &
TestData2 databases located at the I.P. locations
simulated above. Joins are necessary.
Thanks in advance.You can use linked servers and then fully qualify database objects, for
example:
SELECT * FROM SQLServer1.database.dbo.tablename -- from server2
You can find more info about linked servers in books online...
Carlos E. Rojas
SQL Server MVP
Co-Author SQL Server 2000 programming by Example
"DBa" <anonymous@.discussions.microsoft.com> wrote in message
news:639101c3e5cb$e41662e0$a601280a@.phx.gbl...
quote:

> Hi,
> Is it possible to execute a query asking for joined data
> from different tables on two different servers and
> databases?
> SQLServer1 SQLServer2
> -- --
> 09.0.0.30\TestData 198.160.30.20\TestData2
> I need to run a query against tables in the TestData &
> TestData2 databases located at the I.P. locations
> simulated above. Joins are necessary.
> Thanks in advance.
|||alternate solution is to use OPENROWSET if you dont have permissions to
create linked server
Ex:
SELECT a.*
FROM OPENROWSET('SQLOLEDB','server1';'user1';
'password1',
'SELECT * FROM pubs.dbo.authors ORDER BY au_lname, au_fname') AS a
FROM OPENROWSET('SQLOLEDB','server2';'user1';
'password1',
'SELECT * FROM pubs.dbo.titleauthor') AS b
where a.au_id = b.au_id
GO
SQL Booksonline has more samples on OPENROWSET
Sethu Srinivasan
Microsoft Corporation
This posting is provided AS IS with no warranties, and confers no rights.
"Carlos Eduardo Rojas" <carloser@.mindspring.com> wrote in message
news:O2EjQ6h5DHA.2496@.TK2MSFTNGP09.phx.gbl...
quote:

> You can use linked servers and then fully qualify database objects, for
> example:
> SELECT * FROM SQLServer1.database.dbo.tablename -- from server2
> You can find more info about linked servers in books online...
> --
> Carlos E. Rojas
> SQL Server MVP
> Co-Author SQL Server 2000 programming by Example
>
> "DBa" <anonymous@.discussions.microsoft.com> wrote in message
> news:639101c3e5cb$e41662e0$a601280a@.phx.gbl...
>

Query across multiple databases/SQL Servers

Is it possible to run a single query that pulls data from multiple
tables in multiple databases, perhaps also from multiple SQL Servers?
Any input would be appreciated.
Thanks!
RichardFYes. Specify the server and database:
select Select_Column_List
from Server_Name.DB_Name.Object_owner.Table_or_view_name
If from another server, you need to set up a linked server. See Linked
Server in Books Online.
"RichardF" <no.one@.no.where.com> wrote in message
news:41acf571.7680223@.msnews.microsoft.com...
> Is it possible to run a single query that pulls data from multiple
> tables in multiple databases, perhaps also from multiple SQL Servers?
> Any input would be appreciated.
> Thanks!
> RichardF

Query accross servers

Hi,
Please could someone provide me with a best example of how to query records
from different tables in different databases, where the databases are
located on different servers on the same network.
Your assistance is much appreciated.If you want to use different servers you have to build up some linked
servers (look in the BOL). There you can go with the four-point name to
query them.
Select * from [Servername].[Databasename].[owner].[Objectname]
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"11Oppidan" <11Oppidan@.community.nospam> schrieb im Newsbeitrag
news:us3gSr6WFHA.3092@.TK2MSFTNGP10.phx.gbl...
> Hi,
> Please could someone provide me with a best example of how to query
> records from different tables in different databases, where the databases
> are located on different servers on the same network.
> Your assistance is much appreciated.
>|||You may also want to check out OPENQUERY in BOL. Sometimes it yields
better performance than four-part names.
Here's an excerpt from BOL:
This example creates a linked server named OracleSvr against an Oracle
database using the Microsoft OLE DB Provider for Oracle. Then this
example uses a pass-through query against this linked server.
Note This example assumes that an Oracle database alias called ORCLDB
has been created.
EXEC sp_addlinkedserver 'OracleSvr',
'Oracle 7.3',
'MSDAORA',
'ORCLDB'
GO
SELECT *
FROM OPENQUERY(OracleSvr, 'SELECT name, id FROM joe.titles')
GO
HTH...
--
Joe Webb
SQL Server MVP
~~~
Get up to speed quickly with SQLNS
http://www.amazon.com/exec/obidos/t...il/-/0972688811
I support PASS, the Professional Association for SQL Server.
(www.sqlpass.org)
On Wed, 18 May 2005 15:13:15 +0200, "Jens Smeyer"
<Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote:

>If you want to use different servers you have to build up some linked
>servers (look in the BOL). There you can go with the four-point name to
>query them.
>Select * from [Servername].[Databasename].[owner].[Objectname]|||Thanks guys!
"Joe Webb" <joew@.webbtechsolutions.com> wrote in message
news:67gm815emd4m6g2vb7dr70tsn01vsciaon@.
4ax.com...
> You may also want to check out OPENQUERY in BOL. Sometimes it yields
> better performance than four-part names.
> Here's an excerpt from BOL:
> This example creates a linked server named OracleSvr against an Oracle
> database using the Microsoft OLE DB Provider for Oracle. Then this
> example uses a pass-through query against this linked server.
> Note This example assumes that an Oracle database alias called ORCLDB
> has been created.
>
> EXEC sp_addlinkedserver 'OracleSvr',
> 'Oracle 7.3',
> 'MSDAORA',
> 'ORCLDB'
> GO
> SELECT *
> FROM OPENQUERY(OracleSvr, 'SELECT name, id FROM joe.titles')
> GO
>
> HTH...
> --
> Joe Webb
> SQL Server MVP
>
> ~~~
> Get up to speed quickly with SQLNS
> http://www.amazon.com/exec/obidos/t...il/-/0972688811
> I support PASS, the Professional Association for SQL Server.
> (www.sqlpass.org)
>
> On Wed, 18 May 2005 15:13:15 +0200, "Jens Smeyer"
> <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote:
>
>

Query about Ansi-Syntax

I need to write a stored procedure where I need to joing 3 tables A, B and C having approximately 200K, 500K, 800K rows respectively.

Query:
1) If I use ansi-syntax (inner join) as against non-ansi syntax (A.col1 = B.col1), I get a better performance.
Any idea why?

2) If I write a query (shown below), it tries to join table A and B returning large number of rows.

Select A.Col1, A.Col2
from A, B
where A.Col3 = 'xyz'

Why does it try to join the table B with A though there is no join specified.As far as the second query is concerned this is the same as writing

Select A.Col1, A.Col2
from A join B
where A.Col3 = 'xyz'

Basically, don't put the table in the from clause if you are not going to use it because it makes the query REALLY inefficient. This is a cross join and will probably give you heaps of extra records.|||actually, ejustuss, your query generates an error

if we want a cross join, we have to say CROSS JOIN, not just JOIN

and yes, there are many situations where we want to join one table to another, and yet select columns only from one|||This old school syntax can cause a lot of heartburn when you get into multiple outer joins. I do not think MS SQL 2K supports *=

Select A.Col1, A.Col2
from A, B
where A.Col3 = 'xyz'|||I do not think MS SQL 2K supports *=yes, it (still) does
create table Oldschool1
( id tinyint not null primary key identity
, foo varchar(9)
)
insert into Oldschool1 (foo) values ('Curly')
insert into Oldschool1 (foo) values ('Larry')
insert into Oldschool1 (foo) values ('Moe')
insert into Oldschool1 (foo) values ('Shemp')
insert into Oldschool1 (foo) values ('Joe')
insert into Oldschool1 (foo) values ('Curly Joe')

create table Oldschool2
( id tinyint not null primary key identity
, bar varchar(9)
)
insert into Oldschool2 (bar) values ('Curly')
insert into Oldschool2 (bar) values ('Larry')
insert into Oldschool2 (bar) values ('Moe')

select t1.id,t1.foo,t2.id,t2,bar
from Oldschool1 as t1
, Oldschool2 as t2
where t1.foo *= t2.bar
order by 1 :)|||As far as your first question,

The difference between ANSI (inner join) syntax and non-ANSI is that the optimizer will not try to derive joins that are ANSI compliant. That's because you've explicitly defined the joins. The optimizer will have to derive non-ANSI compliant joins. In many cases the query plans will be the same. However there's a greater risk the optimizer won't use the optimal plan if it has to derive the joins.

There's probably some people here that can explain this a lot better than me. Hope this helps.|||As far as your second question,

The results you're getting from that query are called a cartesian product. Since a join hasn't been specified it will match each record from on table to each record from the other. Thus if you have two tables with 100 rows each 10,000 rows will be returned.|||What I was trying to say was that in example 2 of the original post the join was implicit. Sorry about the error in syntax. Where would you want a query of the form

Select A.Col1, A.Col2
from A cross join B
where A.Col3 = 'xyz'

?|||where would you want a cross join?

1. to generate test data, e.g. a large range of dates from integers

2. with a left outer join to find missing many-to-many rows

3. to join a one-row table with application constants such as today's interest rate|||I was actually refering to the query as originally put with no reference to any column in the second table AT ALL. The generation of test data seems like a legitimate use though the other 2 surely require a reference to a column from the 2nd table in the the query somewhere even if only in the join condition.

Its just that I have seen queries with additional tables in the from clause which were unnecessary and unused and actually increased the amount of time taken to run the query substanitially.|||oh, that question

okay, well, the join would be used to ensure existence of a related row, even if you didn't need to actually return any data from the second table

for example, assume car owners are in one table, and parking tickets are in another, you might say "give me the names of every owner who had a parking ticket" and not return any row from the parking ticket table at all|||Well in this case would you not say something along the lines of

select car.owner
from car,ticket
where car.owner = ticket.reciever

?

my point being that you are actually referencing a column from the ticket table in the where clause (or join condition depending on how you write the query) - which is not what is happening in the original example.|||...which is not what is happening in the original example.that's right, it's a cross join

Query a Query with multiple results

Hi,
New to .Net and SQL. I have two tables that I have joined together. RentalControl_Main has the rental informationd and an Adjuster ID that links to the ADjuster table and the adjusters name. I am trying to create a report that gives the "Single" adjuster name and the totals for all of their contracts. I have a details report that gives each contract info. for each specific adjusters rentals. However, I want to just list the adjuster once and give all of their totals. In my SQL statement I have all of it written out and just need to knowwhat to do in place of 'Alex Early' that will give me all of the distinct adjusters.
Do I need to code this on the page with a do while loop?
Appreciate any help.


SELECT SUM(dbo.RentalControl_Main.Rate) / COUNT(dbo.RentalControl_Main.Rate) AS AmtAvg, SUM(dbo.RentalControl_Main.DaysBilled)
/ COUNT(dbo.RentalControl_Main.DaysBilled) AS DayAvg, SUM(dbo.RentalControl_Main.Rate * dbo.RentalControl_Main.DaysBilled)
/ COUNT(dbo.RentalControl_Main.Rate) AS TotAvg
FROM dbo.RentalControl_Main INNER JOIN
dbo.RentalControl_Adjuster ON dbo.RentalControl_Main.AdjusterID = dbo.RentalControl_Adjuster.AdjusterID
WHERE (dbo.RentalControl_Adjuster.AdjusterName = 'Alex Early' AND (dbo.RentalControl_Main.DateClose IS NOT NULL) AND
(dbo.RentalControl_Main.AgencyID = '2')I don't mean to sound off-ish, but do you know much about GROUP BY and DISTINCT?

Query 2 tables - each in a different database

Is there any query code that will allow joining tables that are in different databases running on the same server? If yes, how is the connection to each handled?

That is no problem.

SELECT a.Field, b.Field
FROM dbo.myTable a
JOIN OtherDatabase.dbo.myTable b ON a.myKey = b.myKey

|||

The select code is clear but the connection to the two databases is not when using ADO. Is one connection object used somehow or are the databases linked?

|||

WeslyB is right.

But your user has to have select rights on the other database.

You don't have to handle the rights in ADO.

Regards

Query 2 table in different databases

Is there any query code that will allow joining tables that are in different databases running on the same server? If yes, how is the connection to each handled?

You need to use a 3-part name to reference the table from one database to another. The 3-part name consists of <database>.<schema>.<object>. The connection is only to the server and you can access any database to which you have permissions. You can either switch database context using USE <database> statement or use the 3-part name to reference objects.

Wednesday, March 28, 2012

Query - All from one Table and 'TOP' from another

Hi - Have query structure language question
Hi have two tables,
Table A has a picklist for a field of limited options - say two, X, Y or Z
Table B 'looks up' to those values, so new entrys, must be either X, Y or Z,
but other data is entered, such as a date. So over time there will be many
entries with the linked field being either X, Y or Z, but with a timeline of
dates.
Want I want is a query that will return results for every item in the
picklist (in this case three, X,Y or Z and only the top value (most recent
date) for the date field in Table B.
(FYI - another Table C, links to table A where other fields must be equal.
Thus, what I hope to achieve is that, an entry in the Table C will be
assigned a link to table A, which will inturn return the most up to date
value in Table B.)
Hope someone can help. Ask if you need more detail.
Jon
Jonathan wrote:
> Hi - Have query structure language question
Unfortunately you didn't post any SQL. Instead you posted a word
puzzle. So we have to work out what you meant before we can answer you.
Posting some simple CREATE TABLE statements is a much better way to
describe a problem and it would have saved you some typing too :-)

> Hi have two tables,
> Table A has a picklist for a field of limited options - say two, X, Y or Z
> Table B 'looks up' to those values, so new entrys, must be either X, Y or Z,
> but other data is entered, such as a date. So over time there will be many
> entries with the linked field being either X, Y or Z, but with a timeline of
> dates.
> Want I want is a query that will return results for every item in the
> picklist (in this case three, X,Y or Z and only the top value (most recent
> date) for the date field in Table B.
> (FYI - another Table C, links to table A where other fields must be equal.
> Thus, what I hope to achieve is that, an entry in the Table C will be
> assigned a link to table A, which will inturn return the most up to date
> value in Table B.)
>
Here's my guess:
CREATE TABLE B (x INT NOT NULL, y INT NOT NULL, z INT NOT NULL, dt
DATETIME NOT NULL, PRIMARY KEY (x,y,z,dt /* ? */));
/* Latest date for each x,y,z */
SELECT x,y,z, MAX(dt) AS dt
FROM B
GROUP BY x,y,z ;

> Hope someone can help. Ask if you need more detail.
DDL with keys and other constraints. Sample data (INSERT statements)
and show what end result you want based on that sample data. Also tell
us what version of SQL Server you have.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx

query (deals with exclusions)

I have 2 tables. The first table is a master table with 3 fields: record id, list, and value. The second table is a lookup table that has the list and value in it, as well as fieldname. I need a query that will return a count of records in the master table that do not exist in the lookup table based on list and value. It seems straightforward but my brain doesn't seem to be working. I keep returning the count of records that don't match in the lookup table, instead of the master table. can anyone help? This was my code that isn't working:

select m.list, m.value, count(*)
from master m, lookup l
where m.list = l.list and
m.value <> l.value
and fieldname = 'BOC'
group by m.list, m.value

Thanks in advance.If the columns LIST and VALUE are the joining columns between the MASTER table and the LOOKUP table then try this query:

SELECT COUNT(*)
FROM MASTER m
WHERE NOT EXISTS
(
SELECT *
FROM LOOKUP l
WHERE l.LIST = m.LIST
AND l.VALUE = m.VALUE
)

Friday, March 23, 2012

query

hi everyone

i am trying to join three tables(2 same tables and one different table) and it is taking very long time

here is the query
can anyone optimize the query as it is taking very long time to run

i have 2 tables
tablea
tableb

select * from tablea a1 inner join (select * from tableb where condition) a3
on a1.col1=(select max(col1) from tablea a2
where a3.col2=a2.col2)

i am running this same query based on a condition with col2 and it is working fine and i was using only tables a1 and a3 once.

any suggestions welcome
thanks

Quote:

Originally Posted by LAKS

hi everyone

i am trying to join three tables(2 same tables and one different table) and it is taking very long time

here is the query
can anyone optimize the query as it is taking very long time to run

i have 2 tables
tablea
tableb

select * from tablea a1 inner join (select * from tableb where condition) a3
on a1.col1=(select max(col1) from tablea a2
where a3.col2=a2.col2)

i am running this same query based on a condition with col2 and it is working fine and i was using only tables a1 and a3 once.

any suggestions welcome
thanks


Can u explain your Requirement, then its easy to give sugges|||

Quote:

Originally Posted by LAKS

hi everyone

i am trying to join three tables(2 same tables and one different table) and it is taking very long time

here is the query
can anyone optimize the query as it is taking very long time to run

i have 2 tables
tablea
tableb

select * from tablea a1 inner join (select * from tableb where condition) a3
on a1.col1=(select max(col1) from tablea a2
where a3.col2=a2.col2)

i am running this same query based on a condition with col2 and it is working fine and i was using only tables a1 and a3 once.

any suggestions welcome
thanks


try

Select (all coulmsn from table a)(all columns from table b) from tablea a1 inner join tableb a2 on a1.col = a2.col
where a1.col in (select max(col1) from tablea a2 where a3.col = a2.col)

I was laso wondering if two of the tables are same and have the same data then in might be feasable just to use a1 instaed of a3 in the subquery|||This is probably what you want

select * from tablea a1 where a1.col1 = (
select max(col1) from tablea a2 inner join (select * from tableb where condition) a3 on a3.col2=a2.col2 )

Query

hey,
i have two tables that I want to match, the records that match I want to delete them from the original file and copy them in an other Tabl
Example
Table A Table
1A 3
3B 4
5J 1
All the records that match in that example (1A and 3B), I want to copy them in a new table and delete them only form TableB
I made a join between the two tables, and I have good results. But how to copy and delete them I don't know
Or maybe in Table B I can have a flag that I put on when it is a mached record? But that I nether don't know how to do that in my join query
Thks for help
JacTo copy them to a new table use SELECT.. INTO:
SELECT col1
INTO NewTable
FROM TableA JOIN TableB ON TableA.col1 = TableB.col1
To delete them:
DELETE TableB
FROM TableA JOIN TableB ON TableA.col1 = TableB.col1
--
Carlos E. Rojas
SQL Server MVP
Co-Author SQL Server 2000 Programming by Example
"Jac" <anonymous@.discussions.microsoft.com> wrote in message
news:4B32C95B-5EB4-4F21-8B58-EF0121E17D02@.microsoft.com...
> hey,
> i have two tables that I want to match, the records that match I want to
delete them from the original file and copy them in an other Table
> Example:
> Table A Table B
> 1A 3B
> 3B 4V
> 5J 1A
>
> All the records that match in that example (1A and 3B), I want to copy
them in a new table and delete them only form TableB.
> I made a join between the two tables, and I have good results. But how to
copy and delete them I don't know?
> Or maybe in Table B I can have a flag that I put on when it is a mached
record? But that I nether don't know how to do that in my join query.
> Thks for help.
> Jacsql

query

There are two tables
Expense Table
Amount date
5000 01/01/2004
5000 01/01/2004
100 01/01/2004
Sal Table
Amount date
10000 01/01/2004
400 01/01/2004
500 01/01/2004
100 01/01/2004
expense amount sale amount
5000 10000
5000 400
100 500
100
I want the data like this against 01/01/2004 date, can any body give me
query that how I fulfill that one.
Thanks
NOORYou would be best laying it out in this format client side. Just write
two stored procedures, one to retrieve the expenses and one to retrieve
the sales, both that take a data as a parameter and then process them
client side.
Regards,
William D. Bartholomew
http://blog.bartholomew.id.au/
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||What logic would you use to join these two tables? How do you know, for
instance, that either of the given 5000 expense amounts corresponds to a
given sale (say, the 10000 item you have matched up in your sample output?)
Are there more columns (like, a primary key?)
Please post DDL (full table definitions in SQL), as well as sample data in
the form of INSERT statements.
"Noorali Issani" <naissani@.softhome.net> wrote in message
news:%23FcnRIWPEHA.3748@.TK2MSFTNGP09.phx.gbl...
> There are two tables
> Expense Table
> Amount date
> 5000 01/01/2004
> 5000 01/01/2004
> 100 01/01/2004
> Sal Table
> Amount date
> 10000 01/01/2004
> 400 01/01/2004
> 500 01/01/2004
> 100 01/01/2004
>
> expense amount sale amount
> 5000 10000
> 5000 400
> 100 500
> 100
> I want the data like this against 01/01/2004 date, can any body give me
> query that how I fulfill that one.
> Thanks
> NOOR
>

Query

hey,
i have two tables that I want to match, the records that match I want to del
ete them from the original file and copy them in an other Table
Example:
Table A Table B
1A 3B
3B 4V
5J 1A
All the records that match in that example (1A and 3B), I want to copy them
in a new table and delete them only form TableB.
I made a join between the two tables, and I have good results. But how to co
py and delete them I don't know?
Or maybe in Table B I can have a flag that I put on when it is a mached reco
rd? But that I nether don't know how to do that in my join query.
Thks for help.
JacTo copy them to a new table use SELECT.. INTO:
SELECT col1
INTO NewTable
FROM TableA JOIN TableB ON TableA.col1 = TableB.col1
To delete them:
DELETE TableB
FROM TableA JOIN TableB ON TableA.col1 = TableB.col1
Carlos E. Rojas
SQL Server MVP
Co-Author SQL Server 2000 programming by Example
"Jac" <anonymous@.discussions.microsoft.com> wrote in message
news:4B32C95B-5EB4-4F21-8B58-EF0121E17D02@.microsoft.com...
> hey,
> i have two tables that I want to match, the records that match I want to
delete them from the original file and copy them in an other Table
> Example:
> Table A Table B
> 1A 3B
> 3B 4V
> 5J 1A
>
> All the records that match in that example (1A and 3B), I want to copy
them in a new table and delete them only form TableB.
> I made a join between the two tables, and I have good results. But how to
copy and delete them I don't know?
> Or maybe in Table B I can have a flag that I put on when it is a mached
record? But that I nether don't know how to do that in my join query.
> Thks for help.
> Jac

Wednesday, March 21, 2012

Quering tables in replication

Hi I have an inventory Table that is updated every 1 hr on our stage
database. This then replicates down to our reporting server using
tranactional replication . We have web pages that access the inventory table
on our reporting server and when reporting from this, this is sometimes blank
due to the transactional updates going on. The transactional updates takes 10
to 20 minutes. Does any one have any suggestions where I can keep a table for
reporting services but not in a state when it is not available for longer
then 5 mins or so.
thanks
Sammy
Sammy,
you could issue NOLOCK hints in the reporting query, or force the
distribution agent to work out of hours.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com
(recommended sql server 2000 replication book:
http://www.nwsu.com/0974973602p.html)

Queries using tables from diffrent Databases or SQL instances

Hello,

I am new in SSIS.

I am using an OLEDB source and setted as SQL Command.

The Query is a JOIN between different databases.

How can I make the QUERY with different source (different databases or SQL Servers)?

I mean, any solution is OK, the important is to make queries against different databases with SSIS.

Thank

You can always use two or more OLE DB sources and then use a union all or Merge Join transformations.|||

As Phil wrote in the previous post, you can add several OLEDB sources or others sources and join the data adding a UNION ALL or MERGE JOIN.

In merge Join the input data must be sorted and could ne joined by LEFT or RIGHT.

Regards!

|||

Thank|||

If you have to use an Execute SQL Task, you can do this by creating Linked servers, it can be SQL server or not.

Then use fully qualified names.

I use this to compare tables content side by side accross similar servers.

i.e.

Select s1.ColumnA as Server1_Status, s2.ColumnA as Server2_Status

From Server1 s1

Join Server2 s2 on s1.Pkey = s2.Pkey

Where Server2 is an entry in Server Objects, Linked Servers

For everything else, I use the other options like multiple pumps and Union All.

It performs better, especially when pulling from non-SQL databases.

Regards,

Philippe

Queries mixing two tables (beginner)

I have following two tables in my database:

cars(regnr, brand, owner, inspected)
owner(ssNr, name, adress)

And i would like a queiry with SQL that is the returning the name of all who is owning a Saab. How would that look?

Something like:

SELECT name,
FROM cars, owner WHERE brand = Saab

??

And how do u return regnr and brand of all cars that has not been inspected since 2006-02-22?

Very thankful for your help!

DanneAs I said in your other thread...
You need some form of primary key/foreign key relationship between the two tables. This allows you to join the table together.
What field in the owners table does the owner field in the cars table correspond to?|||What field in the owners table does the owner field in the cars table correspond to?

my guess:

cars(regnr, brand, owner, inspected)
owner(ssNr, name, adress)|||select owner.*
from owner left join cars on cars.owner = owner.ssNr
where cars.brand="SAAB"

something like that?

thank u for all fast answers :)|||no, not quite, but you're close

sorry, but i cannot continue just giving you the answer, i suspect this is homework and you have to try harder

:)|||yes i gotta specify that only the names shall be written out...
after some googling i came to this conclusion??

select owner.*
from owner left join cars on cars.owner = owner.ssNr
where cars.brand="SAAB" order by owner.name|||select owner.*
from owner left join cars on cars.owner = owner.ssNr
where cars.brand="SAAB"

something like that?

Test it!
What are your expected results and do they match the returned values? :D|||Technically, I think it will return all the records Danne expects, but
the join is not quite right.|||it works quite alright :)

RedNeckGeek, i wonder what is wrong with the join?|||I suggest you look at the different types of joins available in SQL.
Google is a source of endless knowledge ;)|||The following stepwise procedure to construct your SELECT qurey might help with this kind of questions:

Step 1. In which table(s) is the information to be found?
==> answer: in CARS and OWNER
==> put down the following part of your query:
FROM cars, owner
Keep in mind that this asks for a "Cartesian product" of the two tables:
any row of CARS is combined with any row of OWNER.

Step 2. Which horizontal restriction do you want to apply to those rows?
==> answer: (a) only those combinations where the field CARS.OWNER equals the OWNER.SSNR field (since other combinations are meaningless)
(b) and from these, only the rows that have CARS.BRAND = 'Saab'
==> put down the following part of your query:
WHERE cars.owner = owner.ssnr AND cars.brand = 'Saab'

Step 3. Do you want to see individual rows, or summary information?
==> answer: individual information
==> so do NOT put any GROUP BY or HAVING clauses.

Step 4. What fields (attributes) do I want to see from each of the remaining rows?
==> answer: the name of the car owner.
==> put down the following part of your query (before the FROM):
SELECT owner.name

In summary, this gives the following:SELECT owner.name
FROM cars, owner
WHERE cars.owner = owner.ssnr AND cars.brand = 'Saab'

As a final check, a useful rule-of-thumb, make sure that there are n-1 "join conditions" in the WHERE clause, where "n" is the number of tables in the FROM clause.
A join condition links a column from one table to a column of an other table.
Here it's the condition cars.owner = owner.ssnr

With too few join conditions, meaningless combinations will be kept (typically visible by the fact that too many rows show up in the end result).

A better way to write the above query, and one where you cannot forget join conditions, is by using the "... INNER JOIN ... ON ... " syntax, but the ingredients and the steps remain the same:SELECT owner.name
FROM cars INNER JOIN owner ON cars.owner = owner.ssnr
WHERE cars.brand = 'Saab'

Using the same procedure could actually lead to a completely other solution (one using a subquery):

Step 1. I need only information from the table OWNER.
==> FROM owner

Step 2. I want to see only those owners that appear in the CARS table with a certain condition there.
==> WHERE ssnr IN (SELECT owner FROM cars WHERE .... )

Step 3: no summary.
Step 4: just the column NAME.
==> SELECT name

Now we are left with the task to create a list of "owner" values from table CARS:

Step 1: which table(s)?
==> FROM cars
Step 2: which horizontal restriction?
==> WHERE cars.brand = 'Saab'

Putting it all together:SELECT name
FROM owner
WHERE ssnr IN (SELECT owner
FROM cars
WHERE brand = 'Saab')
Additional advantage (or disadvantage?) of the latter solution is that persons having several Saabs will only be shown once, while in the first solution they will be shown as many times as their number of Saabs.
(Adding a "DISTINCT" after SELECT would "solve" that, but at the cost of a must slower query than the one with the subquery.)

Queries in productions AND history tables

I've got a large and growing database in SQL Server 7.0. I'd like to utilize a monthly stored procedure that will search various tables for records that are older than 3 months and copy this data out to corresponding history tables. Typically, most production queries are run only on the new data, but occasionally (like at year-end, for example), we will need to run some queries on data extending back 12 months -- that is, on data in the production tables AND in the history tables. Notwithstanding the fact that I've never done stored procedures*, I would like to know if it is possible to run a query that can search for data in both production and history tables at the same time. I know this sounds like a stupid question, but I read somewhere that doing this qould require some kind of Joining function that is complex...?

Thanks,
Whill96205

* Also, any good resources I could use for developing stored procedures?Well that would be a VIEW with a union

And here's a fundamental question...do you have an AD_DT column in all your tables

How big is the database?|||UNION queries can be a little bit tricky, but are not too difficult if both the tables you are pulling from have the same structure. Don't be intimidated.

Select [Column1], [Column2], [Column3]...from CurrentTable
UNION
Select [Column1], [Column2], [Column3]...from HistoryTable

Not so tough, eh?|||Thanks Brett and Blindman. I guess there's no big mystery for unioning then. :)

Well that would be a VIEW with a union

And here's a fundamental question...do you have an AD_DT column in all your tables

How big is the database?

Um... No. What is an AD_DT column?

--whill

P.S. btw, I'm using SQL Server 2000, not 7.0, if that makes any difference.|||Oh - almost forgot. :rolleyes: Regarding database size... The database currently has approximately 43000 records (transactions) in it, increasing by about 100 per day. My task is to incorporate a bunch of related data which the client is currently tracking in several huge spreadsheets. This may nearly double the amount of data, but not necessarily the number of transactions. So I am redesigning the db table structure to better accomdate and utilize the new data that will be imported from the spreadsheets.

Tuesday, March 20, 2012

queries

If I am not in the right newsgroup, please point me to the correct one, I
did not see one that involves queries.
How can I do a query from 2 tables to see which table does not have the same
number of records per person as the 2nd table? I hope that makes sense.
For instance, I have a client table, then 2 other tables related to each
client. One table has invoices, the other has invoices paid (they are
separate tables for other reasons). I want to know which clients have a
different number of invoices than they do invoices paid.
Probably a good question for the .programming group. Can you follow up
there will DDL, sample data and desired results?
http://www.aspfaq.com/
(Reverse address to reply.)
"Rock" <rockisland@.yahoo.com> wrote in message
news:#yFTZfb0EHA.1392@.tk2msftngp13.phx.gbl...
> If I am not in the right newsgroup, please point me to the correct one, I
> did not see one that involves queries.
> How can I do a query from 2 tables to see which table does not have the
same
> number of records per person as the 2nd table? I hope that makes sense.
> For instance, I have a client table, then 2 other tables related to each
> client. One table has invoices, the other has invoices paid (they are
> separate tables for other reasons). I want to know which clients have a
> different number of invoices than they do invoices paid.
>
>
|||As Aaron suggested we really need to see DDL, sample data and expect results
to understand your problem fully. Various questions come to mind. What are
the keys of these tables? Is there a foreign key between them and if so,
what? Do you actually want a count of the invoices or do you just want to
find customers with invoices that don't appear in both tables?
One of these may help. For the first two queries I've assumed that
Invoice_No is the primary key in both tables.
SELECT DISTINCT I.client_id
FROM Invoices AS I
LEFT JOIN PaidInvoices AS P
ON I.invoice_no = P.invoice_no
WHERE P.invoice_no IS NULL
SELECT DISTINCT I.client_id
FROM Invoices AS I
FULL JOIN PaidInvoices AS P
ON I.invoice_no = P.invoice_no
WHERE P.invoice_no IS NULL
OR I.invoice_no IS NULL
SELECT I.client_id, I.invoiced, P.paid
FROM
(SELECT client_id, COUNT(*) AS invoiced
FROM Invoices
GROUP BY client_id) AS I,
(SELECT client_id, COUNT(*) AS paid
FROM PaidInvoices
GROUP BY client_id) AS P
WHERE I.client_id = P.client_id
David Portas
SQL Server MVP
|||Rock,
--This will return all unpaid bills
SELECT * FROM invoices
WHERE NOT EXISTS(SELECT * FROM invoices_paid WHERE
invoices_paid.id=invoices.id)
--This will return all clients and the number of unpaid bills
SELECT COUNT(invoices.id), clients.clients_id FROM invoices
JOIN clients ON clients.clients_id=invoices.clients.id
WHERE NOT EXISTS(SELECT * FROM invoices_paid WHERE
invoices_paid.id=invoices.id)
GROUP BY invoices.id, clients.clients
Regards, Gerald.
"Rock" <rockisland@.yahoo.com> schrieb im Newsbeitrag
news:%23yFTZfb0EHA.1392@.tk2msftngp13.phx.gbl...
> If I am not in the right newsgroup, please point me to the correct one, I
> did not see one that involves queries.
> How can I do a query from 2 tables to see which table does not have the
> same
> number of records per person as the 2nd table? I hope that makes sense.
> For instance, I have a client table, then 2 other tables related to each
> client. One table has invoices, the other has invoices paid (they are
> separate tables for other reasons). I want to know which clients have a
> different number of invoices than they do invoices paid.
>
>

queries

If I am not in the right newsgroup, please point me to the correct one, I
did not see one that involves queries.
How can I do a query from 2 tables to see which table does not have the same
number of records per person as the 2nd table? I hope that makes sense.
For instance, I have a client table, then 2 other tables related to each
client. One table has invoices, the other has invoices paid (they are
separate tables for other reasons). I want to know which clients have a
different number of invoices than they do invoices paid.Probably a good question for the .programming group. Can you follow up
there will DDL, sample data and desired results?
http://www.aspfaq.com/
(Reverse address to reply.)
"Rock" <rockisland@.yahoo.com> wrote in message
news:#yFTZfb0EHA.1392@.tk2msftngp13.phx.gbl...
> If I am not in the right newsgroup, please point me to the correct one, I
> did not see one that involves queries.
> How can I do a query from 2 tables to see which table does not have the
same
> number of records per person as the 2nd table? I hope that makes sense.
> For instance, I have a client table, then 2 other tables related to each
> client. One table has invoices, the other has invoices paid (they are
> separate tables for other reasons). I want to know which clients have a
> different number of invoices than they do invoices paid.
>
>|||As Aaron suggested we really need to see DDL, sample data and expect results
to understand your problem fully. Various questions come to mind. What are
the keys of these tables? Is there a foreign key between them and if so,
what? Do you actually want a count of the invoices or do you just want to
find customers with invoices that don't appear in both tables?
One of these may help. For the first two queries I've assumed that
Invoice_No is the primary key in both tables.
SELECT DISTINCT I.client_id
FROM Invoices AS I
LEFT JOIN PaidInvoices AS P
ON I.invoice_no = P.invoice_no
WHERE P.invoice_no IS NULL
SELECT DISTINCT I.client_id
FROM Invoices AS I
FULL JOIN PaidInvoices AS P
ON I.invoice_no = P.invoice_no
WHERE P.invoice_no IS NULL
OR I.invoice_no IS NULL
SELECT I.client_id, I.invoiced, P.paid
FROM
(SELECT client_id, COUNT(*) AS invoiced
FROM Invoices
GROUP BY client_id) AS I,
(SELECT client_id, COUNT(*) AS paid
FROM PaidInvoices
GROUP BY client_id) AS P
WHERE I.client_id = P.client_id
David Portas
SQL Server MVP
--|||Rock,
--This will return all unpaid bills
SELECT * FROM invoices
WHERE NOT EXISTS(SELECT * FROM invoices_paid WHERE
invoices_paid.id=invoices.id)
--This will return all clients and the number of unpaid bills
SELECT COUNT(invoices.id), clients.clients_id FROM invoices
JOIN clients ON clients.clients_id=invoices.clients.id
WHERE NOT EXISTS(SELECT * FROM invoices_paid WHERE
invoices_paid.id=invoices.id)
GROUP BY invoices.id, clients.clients
Regards, Gerald.
"Rock" <rockisland@.yahoo.com> schrieb im Newsbeitrag
news:%23yFTZfb0EHA.1392@.tk2msftngp13.phx.gbl...
> If I am not in the right newsgroup, please point me to the correct one, I
> did not see one that involves queries.
> How can I do a query from 2 tables to see which table does not have the
> same
> number of records per person as the 2nd table? I hope that makes sense.
> For instance, I have a client table, then 2 other tables related to each
> client. One table has invoices, the other has invoices paid (they are
> separate tables for other reasons). I want to know which clients have a
> different number of invoices than they do invoices paid.
>
>

queries

If I am not in the right newsgroup, please point me to the correct one, I
did not see one that involves queries.
How can I do a query from 2 tables to see which table does not have the same
number of records per person as the 2nd table? I hope that makes sense.
For instance, I have a client table, then 2 other tables related to each
client. One table has invoices, the other has invoices paid (they are
separate tables for other reasons). I want to know which clients have a
different number of invoices than they do invoices paid.Probably a good question for the .programming group. Can you follow up
there will DDL, sample data and desired results?
--
http://www.aspfaq.com/
(Reverse address to reply.)
"Rock" <rockisland@.yahoo.com> wrote in message
news:#yFTZfb0EHA.1392@.tk2msftngp13.phx.gbl...
> If I am not in the right newsgroup, please point me to the correct one, I
> did not see one that involves queries.
> How can I do a query from 2 tables to see which table does not have the
same
> number of records per person as the 2nd table? I hope that makes sense.
> For instance, I have a client table, then 2 other tables related to each
> client. One table has invoices, the other has invoices paid (they are
> separate tables for other reasons). I want to know which clients have a
> different number of invoices than they do invoices paid.
>
>|||As Aaron suggested we really need to see DDL, sample data and expect results
to understand your problem fully. Various questions come to mind. What are
the keys of these tables? Is there a foreign key between them and if so,
what? Do you actually want a count of the invoices or do you just want to
find customers with invoices that don't appear in both tables?
One of these may help. For the first two queries I've assumed that
Invoice_No is the primary key in both tables.
SELECT DISTINCT I.client_id
FROM Invoices AS I
LEFT JOIN PaidInvoices AS P
ON I.invoice_no = P.invoice_no
WHERE P.invoice_no IS NULL
SELECT DISTINCT I.client_id
FROM Invoices AS I
FULL JOIN PaidInvoices AS P
ON I.invoice_no = P.invoice_no
WHERE P.invoice_no IS NULL
OR I.invoice_no IS NULL
SELECT I.client_id, I.invoiced, P.paid
FROM
(SELECT client_id, COUNT(*) AS invoiced
FROM Invoices
GROUP BY client_id) AS I,
(SELECT client_id, COUNT(*) AS paid
FROM PaidInvoices
GROUP BY client_id) AS P
WHERE I.client_id = P.client_id
--
David Portas
SQL Server MVP
--|||Rock,
--This will return all unpaid bills
SELECT * FROM invoices
WHERE NOT EXISTS(SELECT * FROM invoices_paid WHERE
invoices_paid.id=invoices.id)
--This will return all clients and the number of unpaid bills
SELECT COUNT(invoices.id), clients.clients_id FROM invoices
JOIN clients ON clients.clients_id=invoices.clients.id
WHERE NOT EXISTS(SELECT * FROM invoices_paid WHERE
invoices_paid.id=invoices.id)
GROUP BY invoices.id, clients.clients
Regards, Gerald.
"Rock" <rockisland@.yahoo.com> schrieb im Newsbeitrag
news:%23yFTZfb0EHA.1392@.tk2msftngp13.phx.gbl...
> If I am not in the right newsgroup, please point me to the correct one, I
> did not see one that involves queries.
> How can I do a query from 2 tables to see which table does not have the
> same
> number of records per person as the 2nd table? I hope that makes sense.
> For instance, I have a client table, then 2 other tables related to each
> client. One table has invoices, the other has invoices paid (they are
> separate tables for other reasons). I want to know which clients have a
> different number of invoices than they do invoices paid.
>
>