Showing posts with label writing. Show all posts
Showing posts with label writing. Show all posts

Wednesday, March 28, 2012

Query help

Hello everyone,
I need some help building a query using three tables and I am having
difficulty writing the query.
Here are the tables:

GENERAL:
GID - primary key
PARCEL
EDITDATE
MAPCODE

SALES:
GID - foreign key
SLSDATE
SLSAMOUNT

RESIDENCE:
GID - foreign key
OCCUPANCY
LIVINGAREA

The relationship is one-to-many from the General table to both the Sales and
the Residence tables. I want to allow users to query by every field in each
of these tables. The problem is that this is a Sales search, so there must
be a record in the Sales table before it searches all other criteria. How
do I setup the joins for this?
Thanks!
MVMMVM (nospam@.nospam.org) writes:
> Hello everyone,
> I need some help building a query using three tables and I am having
> difficulty writing the query.
> Here are the tables:
> GENERAL:
> GID - primary key
> PARCEL
> EDITDATE
> MAPCODE
>
> SALES:
> GID - foreign key
> SLSDATE
> SLSAMOUNT
>
> RESIDENCE:
> GID - foreign key
> OCCUPANCY
> LIVINGAREA
>
> The relationship is one-to-many from the General table to both the Sales
> and the Residence tables. I want to allow users to query by every field
> in each of these tables. The problem is that this is a Sales search, so
> there must be a record in the Sales table before it searches all other
> criteria. How do I setup the joins for this?

The standard recommendation for this type of question is that you post:

o CREATE TABLE statements for your tables.
o INSERT statements with sample data.
o The desired result given the sample.

This makes it easy to copy and paste and develop a tested solution.

With incomplete information, it goes down to guessworks, which may be
less accurate.

One thing is not clear to me what the result set should look like. If you
have something like:

SELECT ...
FROM general g
JOIN sales s ON g.GID = s.GID
JOIN residence r ON g.GID = r.GID

and for a certain row in general, there are 13 rows in sales and 7
rows in residence, you will get 91 rows in the result with all
combinations of sales and residence. Since this is probably not what
you want, the query about is not the right one. But since I don't know
what you want, I don't what is the right.

Of course, to only find rows in general + residence that have some
match in sales, you can do:

SELECT ...
FROM general g
JOIN residence ON g.GID = r.GID
WHERE EXISTS (SELECT *
FROM sales s
WHERE s.GID = g.GID
AND s.SLSDATE >= '20050201'
AND s.SLSDATE < '20050301')

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||So if you only want to search for things with a row in SALES, you can
start there and outer join the other tables. However, since SALES.GID
is a foreign key to GENERAL, you will always have a row in GENERAL as
well -- so you could start there, also.

I think you want something like this:

select ...
from SALE s
join GENERAL g
on s.GID = g.GID
left outer join RESIDENCE r
on g.GID = r.GID
where ...|||Gentlemen,
Thank you. That is exactly what I needed.

query help

having a spot of trouble writing this one. if you are so inclined and have a
moment, i'd really appreciate your insight.

i have what amounts to a purchase order type of setup...a descriptive header
associated with line items. i have 3 tables...header, lineitem, and
auxiliary. the auxiliary table holds information like subbordinate
information about lineitems that are "non-standard". each of these tables
has a uniqueId column. the lineitem and auxiliary tables have a
parentUniqueId column as well. there is always at least one lineitem whos
parentUniqueId references a header's uniqueId. there are time though, when a
lineitem will reference another lineitem's UniqueId. supplimental data in
the auxiliary table references lineitems in the same fashion except there is
no reflexive self-joining. i know a picture is worth a thousand words, but i
think this is pretty straight-forward.

the data in these tables is sent in xml format via web services to another
server that uses a completely different platform. the web service sends the
status of each record back in xml format confirming which headers,
lineitems, and auxiliary items (by uniqueId) were successfully transfered
and/or which failed. the query i have been trying to write should simply
return the data from all 3 tables as one consolidated record set filtered
such that all related records are returned as long as neither a given,
related header or lineitem or auxiliary where confirmed as failed.

the meat of what i have now is something like:

select items.* ,
a.uniqueId auxId
from
(
select h.uniqueId poId ,
l.uniqueId lineId
from lineItems l
join header h
on h.uniqueId = l.parentUniqueId
union
select h.uniqueId poId ,
child.uniqueId lineId
from lineItems child
join lineItems parent
on child.parentUniqueId = parent.uniqueId
join header h
on h.uniqueId = parent.parentUniqueId
) items
left join auxiliary a
on a.parentUniqueId = items.lineId

this generates the correct view of *all* the data. i need help with the
criterion so that if any related item's uniqueId was said to be "defunct"
then NONE of the other related items should return in the recordset.

thanks for your time, thoughts, and advice.

me (a@.b.com) writes:
> i have what amounts to a purchase order type of setup...a descriptive
> header associated with line items. i have 3 tables...header, lineitem,
> and auxiliary. the auxiliary table holds information like subbordinate
> information about lineitems that are "non-standard". each of these
> tables has a uniqueId column. the lineitem and auxiliary tables have a
> parentUniqueId column as well. there is always at least one lineitem
> whos parentUniqueId references a header's uniqueId. there are time
> though, when a lineitem will reference another lineitem's UniqueId.
> supplimental data in the auxiliary table references lineitems in the
> same fashion except there is no reflexive self-joining. i know a picture
> is worth a thousand words, but i think this is pretty straight-forward.

We can do without the pictures. However, what we are very fond of are:

o CREATE TABLE scripts for the involved tables (preferrably simplified
to cover the essential in the problem)
o Sample statements with INSERT data.
o The desired result given that sample.

There are at least two reasons we like this:

1) By copying-and-pasting the scripts into Query Analyzer, it's easy to
develop a tested solution.
2) It helps to clarify ambiguities in your narrative.

Judging from the problem it appears that there is some status column
somewhere, but I could not find it the text. (Your reluctance to use
the shift key does not really help.) And I wouldn't mind to see an
example how a lineitem can refer to different sort of parent items.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||sorry, ejo...

let's not trifle over the tables save that the all tables have a varchar(50)
column called uniqueId. the lineitem and auxiliary tables have an additional
varchar(50) column called parentUniqueId. let's say the header table's data
looks like:

header (uniqueId is fk to lineitem.parentUniqueId):

uniqueId
A

the lineitem table's data looks like:

lineitem (uniqueId is self-joined by parentUniqueId or an fk to auxiliary):

uniqueId parentUniqueId
X A
Y X
Z X

the aux table's data looks like:

auxiliary:

uniqueId parentUniqueId
L Y
M Z

the query from the previous post would return:

poId lineId auxId
A X
A Y L
A Z M

i'm trying to get only those related items where neither poId, lineId, nor
auxId are in a list of supplied values. i.e. if the list was "QRS", then the
above records *should* show. if the list was "L" for example, then none of
the data above should show...since L is either a poId, lineId, or auxId -
which is the actual case here.|||" " <a@.b.com> wrote in message news:titMe.51039$vb3.17986@.fe07.lga...
> sorry, ejo...
> let's not trifle over the tables save that the all tables have a
varchar(50)
> column called uniqueId. the lineitem and auxiliary tables have an
additional
> varchar(50) column called parentUniqueId. let's say the header table's
data
> looks like:

Let's not "say the header table's data looks like" anything.

Erland's point about providing a real DDL is that folks here can then
recreate your exact configuration, design queries and test them against your
exact schema, not their best guess of your interpretation.

If you have business reasons (as is often the case) for needing to keep
details of your schema secret, break the DDL down to the bare minimum that
accurate describes the problm you're trying to solve.

> header (uniqueId is fk to lineitem.parentUniqueId):
> uniqueId
> A
> the lineitem table's data looks like:
> lineitem (uniqueId is self-joined by parentUniqueId or an fk to
auxiliary):
> uniqueId parentUniqueId
> X A
> Y X
> Z X
> the aux table's data looks like:
> auxiliary:
> uniqueId parentUniqueId
> L Y
> M Z
> the query from the previous post would return:
> poId lineId auxId
> A X
> A Y L
> A Z M
> i'm trying to get only those related items where neither poId, lineId, nor
> auxId are in a list of supplied values. i.e. if the list was "QRS", then
the
> above records *should* show. if the list was "L" for example, then none of
> the data above should show...since L is either a poId, lineId, or auxId -
> which is the actual case here.|||| If you have business reasons (as is often the case) for needing to keep
| details of your schema secret, break the DDL down to the bare minimum that
| accurate describes the problm you're trying to solve.

jesus christ! how much more "bare minimum" does this get:

"all tables have a varchar(50) column called uniqueId. the lineitem and
auxiliary tables have an additional varchar(50) column called
parentUniqueId...i'm trying to get only those related items where neither
poId, lineId, nor auxId are in a list of supplied values."

there is *no* guessing involved. not only have i provided the structure for
each table, their relation to eachother, a sample of what their data looks
like, but i've even written 90% of the goddamn query...i need help with the
criterion! can no one do that?!!|||On Wed, 17 Aug 2005 08:07:30 -0500, wrote:

>| If you have business reasons (as is often the case) for needing to keep
>| details of your schema secret, break the DDL down to the bare minimum that
>| accurate describes the problm you're trying to solve.
>jesus christ! how much more "bare minimum" does this get:
>"all tables have a varchar(50) column called uniqueId. the lineitem and
>auxiliary tables have an additional varchar(50) column called
>parentUniqueId...i'm trying to get only those related items where neither
>poId, lineId, nor auxId are in a list of supplied values."
>there is *no* guessing involved. not only have i provided the structure for
>each table, their relation to eachother, a sample of what their data looks
>like, but i've even written 90% of the goddamn query...i need help with the
>criterion! can no one do that?!!

Hi ,

As Erland already pointed out in his first reply:

"what we are very fond of are:

o CREATE TABLE scripts for the involved tables (preferrably simplified
to cover the essential in the problem)
o Sample statements with INSERT data.
o The desired result given that sample.

There are at least two reasons we like this:

1) By copying-and-pasting the scripts into Query Analyzer, it's easy to
develop a tested solution.
2) It helps to clarify ambiguities in your narrative."

I fully agree with Erland - if you post the requested information, in
the requested form, then I'm quite sure that people can help you. But if
you decline to provide the information in the recommended form, then you
are indeed making it impossible for us to help you.

Some tips for assembling the CREATE TABLE and INSERT statements we need
to help you can be found here: www.aspfaq.com/5006.

And one other suggestion - don't use swear words. Some people are
offended by language like that. And if you are seeking help, offending
those who offer to help for free is generally not a good idea.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)||| (a@.b.com) writes:
> jesus christ! how much more "bare minimum" does this get:
> "all tables have a varchar(50) column called uniqueId. the lineitem and
> auxiliary tables have an additional varchar(50) column called
> parentUniqueId...i'm trying to get only those related items where neither
> poId, lineId, nor auxId are in a list of supplied values."
> there is *no* guessing involved. not only have i provided the structure
> for each table, their relation to eachother, a sample of what their data
> looks like, but i've even written 90% of the goddamn query...i need help
> with the criterion! can no one do that?!!

I read your previous post, but I failed to comprehend:

i'm trying to get only those related items where neither poId, lineId,
nor auxId are in a list of supplied values. i.e. if the list was "QRS",
then the above records *should* show. if the list was "L" for example,
then none of the data above should show...since L is either a poId,
lineId, or auxId - which is the actual case here.

It may be obvious to you, but it is not to me why none of the rows
would be selected when L is in the list.

You may know your business rules and business domain - we don't. And
if you fail to explain me, it's getting difficult to write a query
for you. I mean, you know the business rules, but can still not write
the query.

Anyway, it's all up to you. If you prefer to yell "Jesus Christ",
rather than helping us to help you, please do so.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||| Hi ,

hi, hugo.

| "what we are very fond of are:

well aware by now, i assure you.

| I fully agree with Erland - if you post the requested information, in
| the requested form, then I'm quite sure that people can help you. But if
| you decline to provide the information in the recommended form, then you
| are indeed making it impossible for us to help you.

usually, i agree too. it seems though, (some) people here are incapable of
providing assistance if the post is in *any other form*. i have a problem
with that. there was/is no need to jump through the hoops on this one, as
the most "complex" tables had 2 varchar columns...the other, 1. they related
to eachother in a parent/child,one/many fashion. are you telling me that
that is "hard" to grasp?

far, far from impossible...unless your only modus-operandi is
cut-copy-paste. in that case, i give my condolensces to those with
less-than-normal iqs. that may or may not apply to any of the responders in
this thread...i'm just saying, this was WAY to easy but made WAY too
complex...especially for sooo much bitching.

| Some tips for assembling the CREATE TABLE and INSERT statements we need
| to help you can be found here: www.aspfaq.com/5006.

i'm very...let me say, VERY...experienced with plsql, tsql, and ansi
sql...but, thanks for the link just the same.

| And one other suggestion - don't use swear words. Some people are
| offended by language like that. And if you are seeking help, offending
| those who offer to help for free is generally not a good idea.

i use the words i use. those of which it offends can simply foad (more
sarcastically than actually...pun intended ;^) i'll keep that in mind,
however it seems that unless i fill out the *official help request form*
there is no way i'll be getting help anyway.

i appreciate your input and suggestions, hugo. as it is, i've fixed the
query and have moved on to better things.|||| I read your previous post, but I failed to comprehend:

| It may be obvious to you, but it is not to me why none of the rows
| would be selected when L is in the list.
|
| You may know your business rules and business domain - we don't. And
| if you fail to explain me, it's getting difficult to write a query
| for you. I mean, you know the business rules, but can still not write
| the query.

understood. i do. and, i have.

| Anyway, it's all up to you. If you prefer to yell "Jesus Christ",
| rather than helping us to help you, please do so.

it is, and i've taken care of it. "jesus christ" was frustration and was not
in leu of me helping you help me. as a matter of fact, in each post i've
tried to get everyone to understand what i was going for...but all i got in
return was essentially, "we can't function till we can cut/copy/paste". the
table structure was NOT the issue at all and is NOT difficult to create on
your own...2 columns at most, for CHRIST'S sake. ;^) oh well, no need making
this casm of "official posting format" and "pragmatism" what you want...i
already understand that for most here (at least in this case), the divide is
substancially wide.

anyway, the query runs fine now.||| (a@.b.com) writes:
> the table structure was NOT the issue at all and is NOT difficult to
> create on your own...2 columns at most,

Had the rest of the problem description been clear enough I would maybe
have done it. Or just posted an untested query. But when you don't provide
tables, don't provide INSERT statements, don't provide sample data, and
your description is not clear enough, then the bar is too high for me
being interested in playing guessing games.

You see, it's not that I'm paid to do this or anything.

> anyway, the query runs fine now.

Glad to hear that you got it working.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||| > the table structure was NOT the issue at all and is NOT difficult to
| > create on your own...2 columns at most,
|
| Had the rest of the problem description been clear enough I would maybe
| have done it. Or just posted an untested query. But when you don't provide
| tables, don't provide INSERT statements, don't provide sample data, and
| your description is not clear enough, then the bar is too high for me
| being interested in playing guessing games.

now we enter the realm of "horse-shit". i provided a description of the
tables, just not a create table script. not only that, but i also provided
sample data *and* sample output from the query *i* provided - the response i
got to both of these was: "Let's not 'say the header table's data looks
like' anything." in light of those 2 provisions, the bar was fairly low in
my average estimation...but, i'll give you the benefit-of-the-doubt and
assume you just didn't see my second post *or* the response it got.

each time i posted, i tried to clear up what my aim with the query was but
this was *never* addressed - as each respondant could not get over the
"official post format" condundrum/mantra. i would have tried to better
define this if someone/anyone would have even come close to bucking the
mantra...as no one could, i did not say any more than the first 2 posts
allowed.

| You see, it's not that I'm paid to do this or anything.

cry me a river. i'm a "non-paid" contributer to 3 other newsgroups in which,
my technical prowess is appreciated and respected...even moreso when the op
was vague with defining the problem. i do my best to help each one and i
only get pissed - or become less-than-useful - if the question posted
doesn't relate to the context of the ng. i'm pretty flexible when it comes
to cross and multi posting. this is what i had inadvertantly expected of
contributers here. as this was my first visit here, i will know what to
expect in the future in the way of help...should i ever feel like coming
back! (to which everyone is probably saying, "yeah"...that's fine by me!)

| > anyway, the query runs fine now.
|
| Glad to hear that you got it working.

i do appreciate everyone's participation...i just wish it would have been
more fruitful for all involved.

thanks anyway,

me|||" " <a@.b.com> wrote in news:6oOMe.11796$0E5.3147@.fe05.lga:

> it is, and i've taken care of it. "jesus christ" was frustration and
> was not in leu of me helping you help me. as a matter of fact, in each
> post i've tried to get everyone to understand what i was going
> for...but all i got in return was essentially, "we can't function till
> we can cut/copy/paste". the table structure was NOT the issue at all
> and is NOT difficult to create on your own...2 columns at most, for
> CHRIST'S sake. ;^) oh well, no need making this casm of "official
> posting format" and "pragmatism" what you want...i already understand
> that for most here (at least in this case), the divide is
> substancially wide.

In other words, you're a crybaby who wanted free help, and
then bitched when you got what you paid for.

Nice.||| (a@.b.com) writes:
> now we enter the realm of "horse-shit". i provided a description of the
> tables, just not a create table script. not only that, but i also provided
> sample data *and* sample output from the query *i* provided -

Yeah, you did. But you still did not manage did to explain the problem.

Believe it or not, when we suggest that you should post CREATE TABLE
and all that, it is to help you. And, to some extent a little test:
how much effort are you prepare to lay down yourself.

>| You see, it's not that I'm paid to do this or anything.
> cry me a river. i'm a "non-paid" contributer to 3 other newsgroups in
> which, my technical prowess is appreciated and respected...

Maybe you are. That does however not mean that people here have any
particular reason to spend their free time to guess what you are up to.

And, of course, the attitude you have shown in no way encourages people
to help you.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Nothing is free. but you do get something free on the internet.

John S.
--------------
http://2020ok.com - Free Online Books|||oh, this thread has it all...

Drama, intrigue, and now, commercials!

/grabs popcorn

Monday, March 26, 2012

Query hangs during a seperate write

When writing 100's of records to 1 or more tables within a transaction, the
server seems to hang any query trying to read from those tables until either
a Timeout or the write process completes. I'm not doing a lock.
The writes and reads are separate applications.
What would cause this?How are you doing the write?
AMB
"Joe" wrote:

> When writing 100's of records to 1 or more tables within a transaction, th
e
> server seems to hang any query trying to read from those tables until eith
er
> a Timeout or the write process completes. I'm not doing a lock.
> The writes and reads are separate applications.
> What would cause this?
>
>|||using ADO.NET. The DataAdaptor is doing Inserts into the tables.
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:9960EB96-B274-4A6C-85C0-3BB485E1D411@.microsoft.com...
> How are you doing the write?
>
> AMB
>
> "Joe" wrote:
>
the
either|||Do you know the isolation level being used in the transaction?
You can use Profiler to trace the locks, Lock:Acquired / Lock:Escalation and
Lock:Released.
AMB
"Joe" wrote:

> using ADO.NET. The DataAdaptor is doing Inserts into the tables.
> "Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in messag
e
> news:9960EB96-B274-4A6C-85C0-3BB485E1D411@.microsoft.com...
> the
> either
>
>|||Use with (nolock) on your select statements, for ex.
SELECT au_lname FROM authors WITH (NOLOCK)
This will ensure that select stmt. does the dirty rather than acquiring
an shared lock while the exclusive lock is on.|||You may have a deadlock, and insert is relying on an ID inserted in another
table which itself is waiting for the hanging insert to finish.
If it happens all the time - simply check your logic does the flow work? -
you not done something silly in a transaction.
Otherwise if its intermitant find what process blocks it and syncronise the
order which both processes use DB tables. Try and minimise the time spent in
transactions.
Use profiler to / or current actvity pane in Enterprise man to explore the
processes
Just an approach I've found useful.

Query From ACCCESS to MSDE

First of all...sorry for writing in english.
I'm trying to pass from access to msde.
I have a query that returns some values to populate a listview.
With access this query works in the right way, but in msde i have some
problems .
That's the query
rs.Open "select * from anagp inner join ingrp on anagp.incr = ingrp.rif
where ingrp.lotto='" & ListView2.SelectedItem.SubItems(1) & "' order by
anagp.data desc", cn, adOpenStatic, adLockOptimistic
I've checked out in the immediate window that the query works well but when
I populate the LW I have this problem
li.SubItems(2) = "" & rs("anagp.nome").Value
where li has the dimention of a listitem...
Error: cannot find anag.nome
Why'
Any suggestion will be very apprecitated
Thanx
IAKwhy dont to try adps
"PiantoTardivo" wrote:

> First of all...sorry for writing in english.
> I'm trying to pass from access to msde.
> I have a query that returns some values to populate a listview.
> With access this query works in the right way, but in msde i have some
> problems .
> That's the query
> rs.Open "select * from anagp inner join ingrp on anagp.incr = ingrp.rif
> where ingrp.lotto='" & ListView2.SelectedItem.SubItems(1) & "' order by
> anagp.data desc", cn, adOpenStatic, adLockOptimistic
> I've checked out in the immediate window that the query works well but whe
n
> I populate the LW I have this problem
> li.SubItems(2) = "" & rs("anagp.nome").Value
> where li has the dimention of a listitem...
> Error: cannot find anag.nome
> Why'
> Any suggestion will be very apprecitated
> Thanx
> IAK
>
>|||Looks like zour problem is the name of the column.
1. make sure that the column names are correct, you wrote once anagp.nome
and once anag.nome
2. instead of doing select * ... and then acessing anag(p).nome consider
someting like this:
select anagp.nome as a_nome, ...
and then you can use
rs("a_nome")
to access the column
HTH, Fred
"PiantoTardivo" wrote:

> First of all...sorry for writing in english.
> I'm trying to pass from access to msde.
> I have a query that returns some values to populate a listview.
> With access this query works in the right way, but in msde i have some
> problems .
> That's the query
> rs.Open "select * from anagp inner join ingrp on anagp.incr = ingrp.rif
> where ingrp.lotto='" & ListView2.SelectedItem.SubItems(1) & "' order by
> anagp.data desc", cn, adOpenStatic, adLockOptimistic
> I've checked out in the immediate window that the query works well but whe
n
> I populate the LW I have this problem
> li.SubItems(2) = "" & rs("anagp.nome").Value
> where li has the dimention of a listitem...
> Error: cannot find anag.nome
> Why'
> Any suggestion will be very apprecitated
> Thanx
> IAK
>
>

Friday, March 23, 2012

Query for Tables in a Database...

Good Morning

Shopping for help writing a query for my VB Program to execute against
SQL Server. Here is what I have so far:

SELECT name
FROM sysobjects
WHERE (xtype = 'U')

Is there a way to add to that query to get the list of tables that have the properties COST and PARTNUMBER?

Thanks,
EdUSE Northwind
GO

SELECT *
FROM INFORMATION_SCHEMA.Tables t
WHERE EXISTS (SELECT *
FROM INFORMATION_SCHEMA.Columns c
WHERE t.TABLE_NAME = c.TABLE_NAME
AND c.COLUMN_NAME IN ('Parts','Cost'))
GO|||thanks...

It took me a bit to translate your guidance into what SQL Server wanted.
I ended up with:

select name from sysobjects t where exists( select * from syscolumns c where t.id = c.id
and c.name in ('PartNumber', 'Cost'))
order by name

Thanks,
Ed|||Did you just try and cut and paste the code?

Look up INFORMATION_SCHEMA in Books online...

You want to use those over the system tables.

These are views, which use the system tables...|||IC what you mean now...

Here is what we have now.

SELECT distinct A.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES A, INFORMATION_SCHEMA.COLUMNS B
WHERE A.TABLE_NAME = B.TABLE_NAME
and b.column_name in ('Partnumber', 'Cost')
ORDER BY A.TABLE_NAME

Thanks,
Ed|||Obviously you found out that the join will produce dupTablenames (because of the columns)...why didn't you just use what I gave you?|||the first time I tried it, no results were given. Thought I had to do some
heeby geeby to get it ready for use for my database. But then I noticed
the Parts column reference instead of Partnumber. Changed that and now it runs and returne the proper results.

Thanks,
ED

Tuesday, March 20, 2012

Query every entry not in each hour

Hello,

I have been having a tough time writing the follow requirement for a
query.

On a table that the primary key is a tagId and an hourly timestamp, I
would like to find out for every hour which tags did not get entered
into the database. Essentially I am looking for patterns of entries
that are not making it into tableB.

Examples of the tables:
TableA TableB
TagID and TagName TagId Timestamp
PK PK1 PK2

approx 6000 rows approx 6000 rows per hour

I am thinking that I will need to do something like:

Select tableB1.time, count(*) from tableB1 group by tableB1.time
having tableB1.time >= XXXX and tableB1.time <= XXXX and tableB1.tagId
not in (select tagId from tableA where not exists (select
tableA.tagId, distinct.tableB2.time from tableB2)

I have been trying to create an effecient query handle this but have
not had any luck. Any assistance would be more then appreciated.

Thanks,
AndyThis requires a third tables. It would have a row for every hourly
timestamp, regardless of whether there are rows for that timestamp for
the table you described. You MIGHT get away without that table by
deriving it from TableB, but I suspect that would result in gaps.

The query performs a cross join, then eliminates rows that match
TableB using EXISTS.

SELECT *
FROM TableA as A
CROSS JOIN
TimeStamps as C
WHERE NOT EXISTS
(select * from TableB as B
where A.TagiD = B.TagIC
and C.Timestamp = B.Timestamp)

Roy Harvey
Beacon Falls, CT

On Tue, 17 Jul 2007 17:22:09 -0000, mcdonaghandy@.gmail.com wrote:

Quote:

Originally Posted by

>Hello,
>
>I have been having a tough time writing the follow requirement for a
>query.
>
>On a table that the primary key is a tagId and an hourly timestamp, I
>would like to find out for every hour which tags did not get entered
>into the database. Essentially I am looking for patterns of entries
>that are not making it into tableB.
>
>Examples of the tables:
>TableA TableB
>TagID and TagName TagId Timestamp
>PK PK1 PK2
>
>approx 6000 rows approx 6000 rows per hour
>
>I am thinking that I will need to do something like:
>
>Select tableB1.time, count(*) from tableB1 group by tableB1.time
>having tableB1.time >= XXXX and tableB1.time <= XXXX and tableB1.tagId
>not in (select tagId from tableA where not exists (select
>tableA.tagId, distinct.tableB2.time from tableB2)
>
>I have been trying to create an effecient query handle this but have
>not had any luck. Any assistance would be more then appreciated.
>
>Thanks,
>Andy

Monday, February 20, 2012

Query Assistance - Average Days Between Services

Hi,
I need some help writing a two queries to determine the average number of
days between services for 1. a specific machineid 2. for all specific
machineids.
The table contains many columns including a MachineID column (INT) and a
ServiceDate column (DATETIME) so sample data (excluding other columns) would
look like:
MachineID ServiceDate
123 2005-01-14 00:00:00
123 2005-02-10 00:00:00
123 2005-03-14 00:00:00
124 2005-02-18 00:00:00
123 2005-05-14 00:00:00
124 2005-03-14 00:00:00
124 2005-05-14 00:00:00
The is no IDENTITY column on the table.
So the resultsets would resemble:
1. For a specific machineid
MachineID Average Days Between Services
123 40
2. For all machineids
MachineID Average Days Between Services
123 40
124 42.5
It seems simple but I'm struggling with this one!
Please let me know if you need additional information.
Thanks
JerryJerry,
I think this will do what you want. If you want all MachineID values
listed, even if there is only one ServiceDate, it would help to have a
table of MachineID values, which you can LEFT JOIN so you get
them to appear with NULL average if they appear fewer than twice
in the service table.
If you want the dates to be interpreted correctly in all locales, add
the T between the date and time. The format you are using is not
independent of language and dateformat setting.
Steve Kass
Drew University
set nocount on
go
create table T (
MachineID int,
ServiceDate datetime
)
insert into T values (123,'2005-01-14T00:00:00')
insert into T values (123,'2005-02-10T00:00:00')
insert into T values (123,'2005-03-14T00:00:00')
insert into T values (124,'2005-02-18T00:00:00')
insert into T values (123,'2005-05-14T00:00:00')
insert into T values (124,'2005-03-14T00:00:00')
insert into T values (124,'2005-05-14T00:00:00')
go
select
MachineID, avg(Gap) as AvgGap
from (
select
T1.MachineID,
1.0*datediff(day,T1.ServiceDate,min(T2.ServiceDate)) as Gap
from T as T1
join T as T2
on T2.MachineID = T1.MachineID
where T2.MachineID = T1.MachineID
and T2.ServiceDate > T1.ServiceDate
group by T1.MachineID, T1.ServiceDate
) T
group by MachineID
go
drop table T
Jerry Spivey wrote:

>Hi,
>I need some help writing a two queries to determine the average number of
>days between services for 1. a specific machineid 2. for all specific
>machineids.
>The table contains many columns including a MachineID column (INT) and a
>ServiceDate column (DATETIME) so sample data (excluding other columns) woul
d
>look like:
>MachineID ServiceDate
>123 2005-01-14 00:00:00
>123 2005-02-10 00:00:00
>123 2005-03-14 00:00:00
>124 2005-02-18 00:00:00
>123 2005-05-14 00:00:00
>124 2005-03-14 00:00:00
>124 2005-05-14 00:00:00
>The is no IDENTITY column on the table.
>So the resultsets would resemble:
>1. For a specific machineid
>MachineID Average Days Between Services
>123 40
>2. For all machineids
>MachineID Average Days Between Services
>123 40
>124 42.5
>It seems simple but I'm struggling with this one!
>Please let me know if you need additional information.
>Thanks
>Jerry
>
>
>
>
>
>|||Try,
use northwind
go
create table t1 (
MachineID int not null,
ServiceDate datetime not null,
constraint pk_t1 primary key (MachineID, ServiceDate)
)
go
insert into t1 values(123, '2005-01-14 00:00:00')
insert into t1 values(123, '2005-02-10 00:00:00')
insert into t1 values(123, '2005-03-14 00:00:00')
insert into t1 values(124, '2005-02-18 00:00:00')
insert into t1 values(123, '2005-05-14 00:00:00')
insert into t1 values(124, '2005-03-14 00:00:00')
insert into t1 values(124, '2005-05-14 00:00:00')
go
create view v1
as
select
a.MachineID,
a.ServiceDate,
datediff(day, b.ServiceDate, a.ServiceDate) * 1.0 as days_since_last_serv
from
t1 as a
inner join
t1 as b
on a.MachineID = b.MachineID
and b.ServiceDate = (select max(c.ServiceDate) from t1 as c where
c.MachineID = a.MachineID and c.ServiceDate < a.ServiceDate)
where
datediff(day, b.ServiceDate, a.ServiceDate) is not null
go
select
*
from
v1
order by
MachineID,
ServiceDate
go
select
MachineID,
avg(days_since_last_serv) as [Average Days Between Services]
from
v1
group by
MachineID
order by
MachineID
go
select
MachineID,
avg(days_since_last_serv) as [Average Days Between Services]
from
v1
where
MachineID = 123
group by
MachineID
go
drop view v1
go
drop table t1
go
AMB
"Jerry Spivey" wrote:

> Hi,
> I need some help writing a two queries to determine the average number of
> days between services for 1. a specific machineid 2. for all specific
> machineids.
> The table contains many columns including a MachineID column (INT) and a
> ServiceDate column (DATETIME) so sample data (excluding other columns) wou
ld
> look like:
> MachineID ServiceDate
> 123 2005-01-14 00:00:00
> 123 2005-02-10 00:00:00
> 123 2005-03-14 00:00:00
> 124 2005-02-18 00:00:00
> 123 2005-05-14 00:00:00
> 124 2005-03-14 00:00:00
> 124 2005-05-14 00:00:00
> The is no IDENTITY column on the table.
> So the resultsets would resemble:
> 1. For a specific machineid
> MachineID Average Days Between Services
> 123 40
> 2. For all machineids
> MachineID Average Days Between Services
> 123 40
> 124 42.5
> It seems simple but I'm struggling with this one!
> Please let me know if you need additional information.
> Thanks
> Jerry
>
>
>
>
>
>|||SELECT
MachineID,
(datediff(d, min(ServiceDate), max(ServiceDate))/ (count(machineid)-1)) as
AverageDays FROM TABLE1
GROUP BY MachineId
ORDER BY Machineid
--
Programmer
"Jerry Spivey" wrote:

> Hi,
> I need some help writing a two queries to determine the average number of
> days between services for 1. a specific machineid 2. for all specific
> machineids.
> The table contains many columns including a MachineID column (INT) and a
> ServiceDate column (DATETIME) so sample data (excluding other columns) wou
ld
> look like:
> MachineID ServiceDate
> 123 2005-01-14 00:00:00
> 123 2005-02-10 00:00:00
> 123 2005-03-14 00:00:00
> 124 2005-02-18 00:00:00
> 123 2005-05-14 00:00:00
> 124 2005-03-14 00:00:00
> 124 2005-05-14 00:00:00
> The is no IDENTITY column on the table.
> So the resultsets would resemble:
> 1. For a specific machineid
> MachineID Average Days Between Services
> 123 40
> 2. For all machineids
> MachineID Average Days Between Services
> 123 40
> 124 42.5
> It seems simple but I'm struggling with this one!
> Please let me know if you need additional information.
> Thanks
> Jerry
>
>
>
>
>
>|||CREATE TABLE ServiceLog
(machine_id INTEGER NOT NULL,
service_date DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
CHECK (service_date
= CAST(CEILING (CAST(service_date AS FLOAT)) AS DATETIME)), --drop
time
PRIMARY KEY (machine_id, service_date));
INSERT INTO ServiceLog VALUES (123, '2005-01-14 00:00:00');
INSERT INTO ServiceLog VALUES (123, '2005-02-10 00:00:00');
INSERT INTO ServiceLog VALUES (123, '2005-03-14 00:00:00');
INSERT INTO ServiceLog VALUES (123, '2005-05-14 00:00:00');
INSERT INTO ServiceLog VALUES (124, '2005-02-18 00:00:00');
INSERT INTO ServiceLog VALUES (124, '2005-03-14 00:00:00');
INSERT INTO ServiceLog VALUES (124, '2005-05-14 00:00:00');
SELECT machine_id,
DATEDIFF(DD, MIN(service_date), MAX(service_date))
/ (1.0 *COUNT(*)) AS avg_gap
FROM ServiceLog
GROUP BY machine_id;
This gives me:
macine_id avg_gap
===============
123 30.00
124 28.33
Which look more correct than your 40 days just by eyeballing it -- i.e.
you service things around the 15-th of each month. I did this problem
years ago and got caught in the "procedural mindset" trap like Steve
did. This where you compute each INDIVIDUAL gap between events and
then use an average function on them. Instead think of each machine as
a grouping (subset) that has properties as a whole -- duration range,
and count of events.|||Ok you three are absolutely brilliant!!!
Now just trying to figure out the logic that you used :-) May have a few
questions for you in a few.
Thanks again!!!!
Jerry
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:O5sExXgYFHA.3840@.tk2msftngp13.phx.gbl...
> Hi,
> I need some help writing a two queries to determine the average number of
> days between services for 1. a specific machineid 2. for all specific
> machineids.
> The table contains many columns including a MachineID column (INT) and a
> ServiceDate column (DATETIME) so sample data (excluding other columns)
> would look like:
> MachineID ServiceDate
> 123 2005-01-14 00:00:00
> 123 2005-02-10 00:00:00
> 123 2005-03-14 00:00:00
> 124 2005-02-18 00:00:00
> 123 2005-05-14 00:00:00
> 124 2005-03-14 00:00:00
> 124 2005-05-14 00:00:00
> The is no IDENTITY column on the table.
> So the resultsets would resemble:
> 1. For a specific machineid
> MachineID Average Days Between Services
> 123 40
> 2. For all machineids
> MachineID Average Days Between Services
> 123 40
> 124 42.5
> It seems simple but I'm struggling with this one!
> Please let me know if you need additional information.
> Thanks
> Jerry
>
>
>
>
>|||God, I get sloppy! I forgot to remove one of the days at the end of the
total duration.
SELECT machine_id,
DATEDIFF(DD, MIN(service_date), MAX(service_date))
/ (1.0 *COUNT(*) -1) AS avg_gap
FROM ServiceLog
GROUP BY machine_id;|||Sergey,
If I add only record for a machine I get a divide by zero error. How can I
fix that just in case the data contains only one record for a machineid?
Thanks again.
Jerry
"Sergey Zuyev" <SergeyZuyev@.discussions.microsoft.com> wrote in message
news:6CE8FE0C-FCF0-4E3C-AAF6-F395485F32C4@.microsoft.com...
> SELECT
> MachineID,
> (datediff(d, min(ServiceDate), max(ServiceDate))/ (count(machineid)-1))
> as
> AverageDays FROM TABLE1
> GROUP BY MachineId
> ORDER BY Machineid
> --
> Programmer
>
> "Jerry Spivey" wrote:
>|||I think I got it - added a HAVING COUNT(*) > 1 to the query.
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:%23t5HC4gYFHA.2124@.TK2MSFTNGP14.phx.gbl...
> Sergey,
> If I add only record for a machine I get a divide by zero error. How can
> I fix that just in case the data contains only one record for a machineid?
> Thanks again.
> Jerry
> "Sergey Zuyev" <SergeyZuyev@.discussions.microsoft.com> wrote in message
> news:6CE8FE0C-FCF0-4E3C-AAF6-F395485F32C4@.microsoft.com...
>|||something like that, but im not sure that is the best approach
SELECT
MachineID,
(datediff(d, min(ServiceDate), max(ServiceDate))/ Case
(Count(MachineID)-1) WHEN 0 THEN 1 ELSE (Count(MachineID)-1) END) as
AverageDays FROM TABLE1
GROUP BY MachineId
ORDER BY Machineid
--
Programmer
"Jerry Spivey" wrote:

> Sergey,
> If I add only record for a machine I get a divide by zero error. How can
I
> fix that just in case the data contains only one record for a machineid?
> Thanks again.
> Jerry
> "Sergey Zuyev" <SergeyZuyev@.discussions.microsoft.com> wrote in message
> news:6CE8FE0C-FCF0-4E3C-AAF6-F395485F32C4@.microsoft.com...
>
>