Showing posts with label assistance. Show all posts
Showing posts with label assistance. Show all posts

Saturday, February 25, 2012

Query Assistance.

I am relatively new to the use of coplex queries. Here is a task that I am trying to accomplish.

Source table.

Address ID Workstation Test-a 1 WS1 Test-b 2 WS1 Test-a 5 WS2 Test-d 3 WS2 Test-b 7 WS2

I am trying to write a query that will display this result into Excel.

Address Duplicate WS1 WS2 Test-a
Yes
1
5 Test-b
Yes
2
7 Test-d
No




Basically I am trying to identify if there is a duplicate address, if so mark it as such in the duplicate column and then placing the ID into a column under the Workstation.
I only want to see the duplicated address once (Distinct?) but mark that it is indeed a duplicate and mark the ID's that it has under the workstations.

Any ideas? I have created a query that does pull the data in the first example that is doing a DTS export to excel. However I need to format this to show the second example.

I appreciate any help I can get on this.

What are the possible values for the Workstation column? Is it always at most 2 workstations for any address?|||No, there are actually around 8-10 workstations.
|||

This should give you an idea about how to approach the solution.


Code Snippet


SET NOCOUNT ON


DECLARE @.MyTable table
( RowID int IDENTITY,
Address varchar(20),
[ID] int,
Workstation varchar(20)
)


INSERT INTO @.MyTable VALUES ( 'Test-a', 1, 'WS1' )
INSERT INTO @.MyTable VALUES ( 'Test-b', 2, 'WS1' )
INSERT INTO @.MyTable VALUES ( 'Test-a', 5, 'WS2' )
INSERT INTO @.MyTable VALUES ( 'Test-d', 3, 'WS2' )
INSERT INTO @.MyTable VALUES ( 'Test-b', 7, 'WS2' )


SELECT
Duplicate = CASE WHEN dt.ADDRESS IS NULL THEN 'No' ELSE 'Yes' END,
m.Address,
m.[ID],
m.Workstation
FROM @.MyTable m
LEFT JOIN (SELECT Address
FROM @.MyTable
GROUP BY
Address
HAVING count( Address ) >= 2
) dt
ON m.Address = dt.Address
ORDER BY
Address,
Workstation


Duplicate Address ID Workstation
-- -- --
Yes Test-a 1 WS1
Yes Test-a 5 WS2
Yes Test-b 2 WS1
Yes Test-b 7 WS2
No Test-d 3 WS2

|||I appreciate the information. I have been working with this to pull the data I need. I have modified the insert statement to pull the data from another table.

I am getting an error however:
Server: Msg 209, Level 16, State 1, Line 15
Ambiguous column name 'PointAddress'.

As I mentioned I am new to alot of this, how do I identify line 15? I have searched on the error itself and found references that I should be creating an alias for the "pointaddress" column.

I appreciate the help with this. Explanations will be helpful as well.

Code Snippet

SET NOCOUNT ON

DECLARE @.dup_trnd table
( RowID int IDENTITY,
PointAddress varchar(30),
TrendID int,
Workstation varchar(30)
)

INSERT dup_trnd
SELECT PointAddress,TrendID,Workstation from DuplicateTrends

SELECT
Duplicate = CASE WHEN dt.PointAddress IS NULL THEN 'No' ELSE 'Yes' END,
m.PointAddress,
m.TrendId,
m.Workstation
FROM @.dup_trnd m
LEFT JOIN (SELECT PointAddress
FROM @.dup_trnd
GROUP BY
PointAddress
HAVING count( PointAddress ) >= 2
) dt
ON m.PointAddress = dt.PointAddress
ORDER BY
PointAddress,
Workstation


|||

Try this:


Code Snippet


SET NOCOUNT ON

SELECT
Duplicate = CASE WHEN dt.PointAddress IS NULL THEN 'No' ELSE 'Yes' END,
d.PointAddress,
d.TrendId,
d.Workstation
FROM Dup_Trnd d
LEFT JOIN (SELECT PointAddress
FROM Dup_Trnd
GROUP BY PointAddress
HAVING count( PointAddress ) >= 2
) dt
ON d.PointAddress = dt.PointAddress
ORDER BY
d.PointAddress,
d.Workstation

|||Thank you for the assistance. This is mostly what I need and can work on it from here.

Monday, February 20, 2012

query assistance -return most recent date

I have a table that has two fields, pkg_num, which is a number, and
del_date_time, which is a date-time. The table can contain duplicate pkg_num
values, as long as the del_date_time values are different for any given
number. I need a query that will return the most recent del_date_time for
each pkg_num. Any ideas?
On Thu, 10 Feb 2005 09:17:01 -0800, Rich_A2B wrote:

>I have a table that has two fields, pkg_num, which is a number, and
>del_date_time, which is a date-time. The table can contain duplicate pkg_num
>values, as long as the del_date_time values are different for any given
>number. I need a query that will return the most recent del_date_time for
>each pkg_num. Any ideas?
Hi Rich_A2B,
Probably
SELECT pkg_num, MAX(del_date_time)
FROM MyTable
GROUP BY pkg_num
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||That works, thanks! Now to complicate things, I have a third field,
DEL_RECIP_NAME. There can exist records where PKG_NUM is the same, but both
DEL_DATE_TIME and DEL_RECIP_NAME are different. How do I show all three
fields in the query result, but only show records with the most recent
DEL_DATE_TIME?
"Hugo Kornelis" wrote:

> On Thu, 10 Feb 2005 09:17:01 -0800, Rich_A2B wrote:
>
> Hi Rich_A2B,
> Probably
> SELECT pkg_num, MAX(del_date_time)
> FROM MyTable
> GROUP BY pkg_num
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>
|||On Fri, 11 Feb 2005 08:35:07 -0800, Rich_A2B wrote:

>That works, thanks! Now to complicate things, I have a third field,
>DEL_RECIP_NAME. There can exist records where PKG_NUM is the same, but both
>DEL_DATE_TIME and DEL_RECIP_NAME are different. How do I show all three
>fields in the query result, but only show records with the most recent
>DEL_DATE_TIME?
Hi Rich_A2B,
I guess I should have seen that one coming :-)
SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
WHERE NOT EXISTS (SELECT *
FROM MyTable AS b
WHERE b.pkg_num = a.pkg_num
AND b.del_date_time > a.del_date_tim)
or
SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
INNER JOIN (SELECT pkg_num, MAX(del_date_time) AS max_del_date_time
FROM MyTable
GROUP BY pkg_num) AS b
ON a.pkg_num = b.pkg_num
AND a.del_date_time = b.max_del_date_time
or
SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
WHERE a.del_date_time = (SELECT MAX(del_date_time)
FROM MyTable AS b
WHERE b.pkg_num = a.pkg_num)
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||*** Sent via Developersdex http://www.codecomments.com ***
Don't just participate in USENET...get rewarded for it!
|||

Quote:

Originally posted by Hugo Kornelis
On Fri, 11 Feb 2005 08:35:07 -0800, Rich_A2B wrote:

>That works, thanks! Now to complicate things, I have a third field,
>DEL_RECIP_NAME. There can exist records where PKG_NUM is the same, but both
>DEL_DATE_TIME and DEL_RECIP_NAME are different. How do I show all three
>fields in the query result, but only show records with the most recent
>DEL_DATE_TIME?
Hi Rich_A2B,
I guess I should have seen that one coming :-)
SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
WHERE NOT EXISTS (SELECT *
FROM MyTable AS b
WHERE b.pkg_num = a.pkg_num
AND b.del_date_time > a.del_date_tim)
or
SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
INNER JOIN (SELECT pkg_num, MAX(del_date_time) AS max_del_date_time
FROM MyTable
GROUP BY pkg_num) AS b
ON a.pkg_num = b.pkg_num
AND a.del_date_time = b.max_del_date_time
or
SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
WHERE a.del_date_time = (SELECT MAX(del_date_time)
FROM MyTable AS b
WHERE b.pkg_num = a.pkg_num)
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)

Query Assistance Requested.. Summing Data

Howdy gang,
Quick query question for the query gurus
I want to crete a query that SUMs a field for the last 7 records in its
own field.
Here is my @.example table
Date Money
1/1/01 $100
1/2/01 $200
1/3/01 $300
1/4/01 $100
1/5/01 $200
1/6/01 $200
1/7/01 $500
1/8/01 $200
1/9/01 $400
1/10/01 $100
1/11/01 $200
1/12/01 $100
1/13/01 $100
1/14/01 $200
1/15/01 $700
1/16/01 $100
1/17/01 $400
**This is what I am running**
Select Date, Money,
Case When (Select DATENAME(dw,Date)) = 'Monday'
Then (Select SUM(Money) from @.Example
Where Date between DateAdd(Day,-7,Date) and Date)
Else NULL End as WeekSalesTotal
>From @.Example
What I am trying to accomplish:
When it is Monday, I want to add the previous 7 days Money together
into a new field we will call WeekSalesTotal. All records for days
other than Monday the WeekSalesTotal field would be NULL. My table
should look like following if done correctly.
Date Money WeekSalesTotal
1/1/01 $100 $100
1/2/01 $200 NULL
1/3/01 $300 NULL
1/4/01 $100 NULL
1/5/01 $200 NULL
1/6/01 $200 NULL
1/7/01 $500 NULL
1/8/01 $200 $1500
1/9/01 $400 NULL
1/10/01 $100 NULL
1/11/01 $200 NULL
1/12/01 $100 NULL
1/13/01 $100 NULL
1/14/01 $200 NULL
1/15/01 $700 $1800
1/16/01 $100 NULL
1/17/01 $400 NULL
I have been staring at this issue for a little bit and was hoping fresh
eyes on it would help.
Thank You
On 2 Nov 2005 09:37:44 -0800, EvilReportingGenius wrote:
(snip)[vbcol=seagreen]
>**This is what I am running**
>Select Date, Money,
> Case When (Select DATENAME(dw,Date)) = 'Monday'
> Then (Select SUM(Money) from @.Example
> Where Date between DateAdd(Day,-7,Date) and Date)
> Else NULL End as WeekSalesTotal
Hi EvilReportingGenius,
Try what happens if you change this to:
Select Date, Money,
Case When (Select DATENAME(dw,Date)) = 'Monday'
Then (Select SUM(Money) from @.Example AS b
Where b.Date between DateAdd(Day,-7,a.Date) and a.Date)
Else NULL End as WeekSalesTotal
From @.Example AS a
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)

Query Assistance Requested.. Summing Data

Howdy gang,
Quick query question for the query gurus
I want to crete a query that SUMs a field for the last 7 records in its
own field.
Here is my @.example table
Date Money
--
1/1/01 $100
1/2/01 $200
1/3/01 $300
1/4/01 $100
1/5/01 $200
1/6/01 $200
1/7/01 $500
1/8/01 $200
1/9/01 $400
1/10/01 $100
1/11/01 $200
1/12/01 $100
1/13/01 $100
1/14/01 $200
1/15/01 $700
1/16/01 $100
1/17/01 $400
**This is what I am running**
Select Date, Money,
Case When (Select DATENAME(dw,Date)) = 'Monday'
Then (Select SUM(Money) from @.Example
Where Date between DateAdd(Day,-7,Date) and Date)
Else NULL End as WeekSalesTotal
>From @.Example
What I am trying to accomplish:
When it is Monday, I want to add the previous 7 days Money together
into a new field we will call WeekSalesTotal. All records for days
other than Monday the WeekSalesTotal field would be NULL. My table
should look like following if done correctly.
Date Money WeekSalesTotal
--
1/1/01 $100 $100
1/2/01 $200 NULL
1/3/01 $300 NULL
1/4/01 $100 NULL
1/5/01 $200 NULL
1/6/01 $200 NULL
1/7/01 $500 NULL
1/8/01 $200 $1500
1/9/01 $400 NULL
1/10/01 $100 NULL
1/11/01 $200 NULL
1/12/01 $100 NULL
1/13/01 $100 NULL
1/14/01 $200 NULL
1/15/01 $700 $1800
1/16/01 $100 NULL
1/17/01 $400 NULL
I have been staring at this issue for a little bit and was hoping fresh
eyes on it would help.
Thank YouOn 2 Nov 2005 09:37:44 -0800, EvilReportingGenius wrote:
(snip)
>**This is what I am running**
>Select Date, Money,
> Case When (Select DATENAME(dw,Date)) = 'Monday'
> Then (Select SUM(Money) from @.Example
> Where Date between DateAdd(Day,-7,Date) and Date)
> Else NULL End as WeekSalesTotal
>>From @.Example
Hi EvilReportingGenius,
Try what happens if you change this to:
Select Date, Money,
Case When (Select DATENAME(dw,Date)) = 'Monday'
Then (Select SUM(Money) from @.Example AS b
Where b.Date between DateAdd(Day,-7,a.Date) and a.Date)
Else NULL End as WeekSalesTotal
From @.Example AS a
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Query Assistance Requested.. Summing Data

Howdy gang,
Quick query question for the query gurus
I want to crete a query that SUMs a field for the last 7 records in its
own field.
Here is my @.example table
Date Money
--
1/1/01 $100
1/2/01 $200
1/3/01 $300
1/4/01 $100
1/5/01 $200
1/6/01 $200
1/7/01 $500
1/8/01 $200
1/9/01 $400
1/10/01 $100
1/11/01 $200
1/12/01 $100
1/13/01 $100
1/14/01 $200
1/15/01 $700
1/16/01 $100
1/17/01 $400
**This is what I am running**
Select Date, Money,
Case When (Select DATENAME(dw,Date)) = 'Monday'
Then (Select SUM(Money) from @.Example
Where Date between DateAdd(Day,-7,Date) and Date)
Else NULL End as WeekSalesTotal
>From @.Example
What I am trying to accomplish:
When it is Monday, I want to add the previous 7 days Money together
into a new field we will call WeekSalesTotal. All records for days
other than Monday the WeekSalesTotal field would be NULL. My table
should look like following if done correctly.
Date Money WeekSalesTotal
--
1/1/01 $100 $100
1/2/01 $200 NULL
1/3/01 $300 NULL
1/4/01 $100 NULL
1/5/01 $200 NULL
1/6/01 $200 NULL
1/7/01 $500 NULL
1/8/01 $200 $1500
1/9/01 $400 NULL
1/10/01 $100 NULL
1/11/01 $200 NULL
1/12/01 $100 NULL
1/13/01 $100 NULL
1/14/01 $200 NULL
1/15/01 $700 $1800
1/16/01 $100 NULL
1/17/01 $400 NULL
I have been staring at this issue for a little bit and was hoping fresh
eyes on it would help.
Thank YouOn 2 Nov 2005 09:37:44 -0800, EvilReportingGenius wrote:
(snip)[vbcol=seagreen]
>**This is what I am running**
>Select Date, Money,
> Case When (Select DATENAME(dw,Date)) = 'Monday'
> Then (Select SUM(Money) from @.Example
> Where Date between DateAdd(Day,-7,Date) and Date)
> Else NULL End as WeekSalesTotal
Hi EvilReportingGenius,
Try what happens if you change this to:
Select Date, Money,
Case When (Select DATENAME(dw,Date)) = 'Monday'
Then (Select SUM(Money) from @.Example AS b
Where b.Date between DateAdd(Day,-7,a.Date) and a.Date)
Else NULL End as WeekSalesTotal
From @.Example AS a
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Query assistance or advice

Hi,
I have a table which I copy nightly via DTS. I would like to copy only the
data which was changed instead based on the MODIFIED date. It will have to
insert any new rows created or update any row
which already exists. This is a sample
TABLE1
ID PRODID NAME QTY MODIFIED
1 123 TEST 1 2006-02-09
2 235 TEST2 2 2006-02-09
3 234 TEST3 5 2006-02-09
TABLE2 (MIRROR)
ID PRODID NAME QTY MODIFIED
1 123 TEST 5 2006-02-07
In this case when I run the query it will update TABLE2 by
updating the qty for id 1 to 1
insert id 2 and 3
Any ideas?
ThanksWhy don't you use triggers? There are several good examples in Books Online.
ML
http://milambda.blogspot.com/|||Doesn't DTS have tools for this? How are you using DTS? I think it has
tools to let you do this directly into table2, checking to see if it needs
to be done.
If you pumping the data right into a temporary table and then running a
query? If so then just write a query like :
insert into table2 (columnList)
select (columnList)
from table1changes as table1
where not exists (select 1
from table2
where table1.id = table2.id)
update table2
set table2.(each column) = table1.(each column)
from table2
join table1changes as table1
on table2.id = table1.id --this must be unique or you
will get (predictably) wierd results
and table1.modified <> table2.modified
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"Arguments are to be avoided: they are always vulgar and often convincing."
(Oscar Wilde)
"Chris" <Chris@.discussions.microsoft.com> wrote in message
news:A8518925-0EB0-4D7D-8BD6-2C4FFBE686E4@.microsoft.com...
> Hi,
> I have a table which I copy nightly via DTS. I would like to copy only the
> data which was changed instead based on the MODIFIED date. It will have to
> insert any new rows created or update any row
> which already exists. This is a sample
> TABLE1
> ID PRODID NAME QTY MODIFIED
> 1 123 TEST 1 2006-02-09
> 2 235 TEST2 2 2006-02-09
> 3 234 TEST3 5 2006-02-09
> TABLE2 (MIRROR)
> ID PRODID NAME QTY MODIFIED
> 1 123 TEST 5 2006-02-07
>
> In this case when I run the query it will update TABLE2 by
> updating the qty for id 1 to 1
> insert id 2 and 3
> Any ideas?
> Thanks|||I am importing from a legacy database. I am currently transferring the entir
e
table nightly but it's hugh so we added a modifieddate column to the table s
o
now I want to check for any records added and updated for a specific date
then check my table in sql server, if records does not exists then insert
them if they do exists then update.
Thanks
"Chris" wrote:

> Hi,
> I have a table which I copy nightly via DTS. I would like to copy only the
> data which was changed instead based on the MODIFIED date. It will have to
> insert any new rows created or update any row
> which already exists. This is a sample
> TABLE1
> ID PRODID NAME QTY MODIFIED
> 1 123 TEST 1 2006-02-09
> 2 235 TEST2 2 2006-02-09
> 3 234 TEST3 5 2006-02-09
> TABLE2 (MIRROR)
> ID PRODID NAME QTY MODIFIED
> 1 123 TEST 5 2006-02-07
>
> In this case when I run the query it will update TABLE2 by
> updating the qty for id 1 to 1
> insert id 2 and 3
> Any ideas?
> Thanks|||For DTS I am using a transform data task form one data source to the other.
What tools are you talking about?
"Louis Davidson" wrote:

> Doesn't DTS have tools for this? How are you using DTS? I think it has
> tools to let you do this directly into table2, checking to see if it needs
> to be done.
> If you pumping the data right into a temporary table and then running a
> query? If so then just write a query like :
> insert into table2 (columnList)
> select (columnList)
> from table1changes as table1
> where not exists (select 1
> from table2
> where table1.id = table2.id)
> update table2
> set table2.(each column) = table1.(each column)
> from table2
> join table1changes as table1
> on table2.id = table1.id --this must be unique or you
> will get (predictably) wierd results
> and table1.modified <> table2.modified
> --
> ----
--
> Louis Davidson - http://spaces.msn.com/members/drsql/
> SQL Server MVP
> "Arguments are to be avoided: they are always vulgar and often convincing.
"
> (Oscar Wilde)
> "Chris" <Chris@.discussions.microsoft.com> wrote in message
> news:A8518925-0EB0-4D7D-8BD6-2C4FFBE686E4@.microsoft.com...
>
>|||I don't know. I am a query/design guy. DTS is a tool I have heard about
and read about but never put into practice. I would think that the
transform task might be able to do a query to check for row existance (maybe
someone else will know?)
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"Arguments are to be avoided: they are always vulgar and often convincing."
(Oscar Wilde)
"Chris" <Chris@.discussions.microsoft.com> wrote in message
news:F2580A5F-1EEB-4120-82C3-0CE0FF6FEA9C@.microsoft.com...
> For DTS I am using a transform data task form one data source to the
> other.
> What tools are you talking about?
> "Louis Davidson" wrote:
>

Query Assistance Needed - Please

Alright, I have this table called Tags. The three columns of interest
are Tags.Id, Tags.Name, Tags.ParentTagId

This is the query I am currently using:

Select Tags.Id, Tags.Name, Tags.ParentTagId

Quote:

Originally Posted by

>From Tags


WHERE Tags.Id IN (
22536,
22535
)

This outputs to:

Id Name ParentTagId
-- ---- -----
22535 Courses 148
22536 AEB3300-2204 22535

Obviously, Courses is the Parent Tag Name to AEB3300-2204. How can I
get this to show up so the results are something like

Id Name ParentTagId ParentTagName
-- ---- -----
-----
22535 Courses 148 SomeName
22536 AEB3300-2204 22535 Courses

Thank you all for your help! I truly appreciate it!Hi there,

I think this would work:

===========================================
select T1.id, T1.name, T1.ParentTagId, T2.Name As ParentTagName
fromTags T1,
Tags T2
whereT1.ParentTagId = t2.Id
===========================================

Thanks,

Marc

Andrew Tatum wrote:

Quote:

Originally Posted by

Alright, I have this table called Tags. The three columns of interest
are Tags.Id, Tags.Name, Tags.ParentTagId
>
This is the query I am currently using:
>
Select Tags.Id, Tags.Name, Tags.ParentTagId

Quote:

Originally Posted by

From Tags


WHERE Tags.Id IN (
22536,
22535
)
>
This outputs to:
>
Id Name ParentTagId
-- ---- -----
22535 Courses 148
22536 AEB3300-2204 22535
>
Obviously, Courses is the Parent Tag Name to AEB3300-2204. How can I
get this to show up so the results are something like
>
Id Name ParentTagId ParentTagName
-- ---- -----
-----
22535 Courses 148 SomeName
22536 AEB3300-2204 22535 Courses
>
Thank you all for your help! I truly appreciate it!

|||You should get a copy of TREES & HIERARCHIES IN SQL for other ways to
mode this in SQL.

Query Assistance Needed - Please

Alright, I have this table called Tags. The three columns of interest
are Tags.Id, Tags.Name, Tags.ParentTagId

This is the query I am currently using:

Select Tags.Id, Tags.Name, Tags.ParentTagId

Quote:

Originally Posted by

>From Tags


WHERE Tags.Id IN (
22536,
22535
)

This outputs to:

Id Name ParentTagId
-- ---- -----
22535 Courses 148
22536 AEB3300-2204 22535

Obviously, Courses is the Parent Tag Name to AEB3300-2204. How can I
get this to show up so the results are something like

Alright, I have this table called Tags. The three columns of interest
are Tags.Id, Tags.Name, Tags.ParentTagId

This is the query I am currently using:

Select Tags.Id, Tags.Name, Tags.ParentTagId

Quote:

Originally Posted by

>From Tags


WHERE Tags.Id IN (
22536,
22535
)

This outputs to:

Id Name ParentTagId ParentTagName
-- ---- -----
-----
22535 Courses 148 SomeName
22536 AEB3300-2204 22535 Courses

Thank you all for your help! I truly appreciate it!Sorry about the above. I copied it to verify spelling, etc and
apparently instead of replacing the text it posted below it. I
apologize!

Query Assistance for Newbie

I need to modify a query through which I've done mostly using the Query
builder in Enterprise Manager so it can be run periodically without manual
editing. The query builder creates the following text:

select [ATHSTATDATA].[NSTATEVENTID] as "Page or
Search",[ATHSTATDATA].[NDATA] as "Hits if Search", [ATHSTATDATA].[VCDATA] as
"Topic or Search String", [ATHSTATDATA].[DTTIMESTAMP] as "Time of Activity"
from [ATHSTATDATA]
where [ATHSTATDATA].[DTTIMESTAMP]<'4/30/2004 12:00:00 AM' AND
[ATHSTATDATA].[DTTIMESTAMP]>'4/23/2004 12:00:00 AM'
order by [ATHSTATDATA].[DTTIMESTAMP]

What I need to do is to replace the specific dates (<'4/30/2004 12:00:00
AM', '4/23/2004 12:00:00 AM') so that I get only rows created from the time
at which the query is run and back 7 days. Thanks in advance for whatever
help you can provide!...
WHERE dttimestamp
BETWEEN CAST(DATEDIFF(DAY,7,CURRENT_TIMESTAMP) AS DATETIME)
AND CURRENT_TIMESTAMP

--
David Portas
SQL Server MVP
--|||David Portas (REMOVE_BEFORE_REPLYING_dportas@.acm.org) writes:
> ...
> WHERE dttimestamp
> BETWEEN CAST(DATEDIFF(DAY,7,CURRENT_TIMESTAMP) AS DATETIME)
> AND CURRENT_TIMESTAMP

WHERE dttimestamp
BETWEEN dateadd(DAY, -7, CURRENT_TIMESTAMP) AND CURRENT_TIMESTAMP

Would be somewhat less cryptic, and not rely on undocumented
conversion between integer and datetime.

Now, Ray said:

so that I get only rows created from the time at which the query is run
and back 7 days.

Which the above does on the hour, but Roy's sample query indicated that
he wanted it by calender day. In such we should write:

BETWEEN dateadd(DAY, -7, convert(char(8), CURRENT_TIMESTAMP, 112) AND
CURRENT_TIMESTAMP

This still not match the original query, as this had < and >, but
I don't really know what Ray means with today, I have to stop there.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

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

Query Assistance Combining Columns into one

I have a query that gets three columns of data. PRODUCT_ID, SMALL_TEXT_VALUE, AND LARGE_TEXT_VALUE. I'd like to know if there is a way that I can alter my query below so that whenever SMALL_TEXT_VALUE is Null, it uses the value thats in the LARGE_TEXT_VALUE column. Whenever the small is null, the data I need is in the large column.

My Query:

Select EXTENDED_ATTRIBUTE_VALUES.PRODUCT_ID, EXTENDED_ATTRIBUTE_VALUES.SMALL_TEXT_VALUE, EXTENDED_ATTRIBUTE_VALUES.LARGE_TEXT_VALUE
From EXTENDED_ATTRIBUTE_VALUES, EXTENDED_ATTRIBUTES
Where EXTENDED_ATTRIBUTE_VALUES.Ext_Att_ID = EXTENDED_ATTRIBUTES.Ext_Att_ID
ORDER BY Product_ID DESC

ISNULL(small_text_value,large_text_value) AS TheValue|||

This would return large_Text when small_text is null. but notice if small_text is null you will get 2 columns with same value. If that is not what you want please post back with more details.

SELECTEAV.PRODUCT_ID,CASEWHEN EAV.SMALL_TEXT_VALUEISNULLTHEN EAV.LARGE_TEXT_VALUEELSE EAV.SMALL_TEXT_VALUEEND , EAV.LARGE_TEXT_VALUEFROMEXTENDED_ATTRIBUTE_VALUES EAVINNERJOIN EXTENDED_ATTRIBUTES EAWHERE EAV.Ext_Att_ID = EA.Ext_Att_IDORDER BY Product_IDDESC

|||

Or

COALESCE(small_text_value,large_text_value) AS TheValue

If the small is null, the data will be from the large column.

|||

Everyones solutions worked perfect. Thanks!

I've now got something else I need to do. To build this info, I need to pull from a few different tables.

I now have the query that we just worked on, and I set it equal to the column of data I need:

Select EXTENDED_ATTRIBUTE_VALUES.PRODUCT_ID, ISNULL(small_text_value,large_text_value) AS TheValue, EXTENDED_ATTRIBUTES.Column_Name
From EXTENDED_ATTRIBUTE_VALUES, EXTENDED_ATTRIBUTES
Where EXTENDED_ATTRIBUTE_VALUES.Ext_Att_ID = EXTENDED_ATTRIBUTES.Ext_Att_ID And
EXTENDED_ATTRIBUTES.Column_Name = '4 Ball EP'
ORDER BY Product_ID DESC

And I now also need the rows from this query:

Select PRODUCT_FEATURE_VALUES.PRODUCT_ID, SHARED_FEATURE_VALUES.Feature_Text_Value As TheValue
From PRODUCT_FEATURE_VALUES, SHARED_FEATURE_TYPES, SHARED_FEATURE_VALUES
Where PRODUCT_FEATURE_VALUES.Feature_Type_ID = SHARED_FEATURE_TYPES.Feature_Type_ID And
SHARED_FEATURE_TYPES.Feature_Type = '4 Ball EP' And
PRODUCT_FEATURE_VALUES.Feature_Value_ID = SHARED_FEATURE_VALUES.Feature_Value_ID

I'd like them to both return in one query if thats possible...

|||If the columns are the same I think you could use a Union statement.|||

I used a Union and that works. I now have:

Select
PRODUCT_FEATURE_VALUES.PRODUCT_ID AS ProductID,
SHARED_FEATURE_VALUES.Feature_Text_Value As TheValue,
SHARED_FEATURE_TYPES.Feature_Type AS ColumnName
From PRODUCT_FEATURE_VALUES, SHARED_FEATURE_TYPES, SHARED_FEATURE_VALUES
Where
PRODUCT_FEATURE_VALUES.Feature_Type_ID = SHARED_FEATURE_TYPES.Feature_Type_ID And
PRODUCT_FEATURE_VALUES.Feature_Value_ID = SHARED_FEATURE_VALUES.Feature_Value_ID
UNION

Select
EXTENDED_ATTRIBUTE_VALUES.PRODUCT_ID AS ProductID,
ISNULL(small_text_value,large_text_value) AS TheValue,
EXTENDED_ATTRIBUTES.Column_Name AS ColumnName
From EXTENDED_ATTRIBUTE_VALUES, EXTENDED_ATTRIBUTES
Where EXTENDED_ATTRIBUTE_VALUES.Ext_Att_ID = EXTENDED_ATTRIBUTES.Ext_Att_ID
ORDER BY Product_ID DESC

How can I display the values in a column as a column. In the 2 fields above that I'm declaring as ColumnName, there are alot of individual values. How can I make one of those values the columnname, and if I want another and so on... I'm trying to build an app for some internal querying and if the user says I want to see all values for A and B, then I would want to display A and B as individual columns, even though they are just a value in the same column of data in the database.

|||

SELECT t1.ProductID,MAX(CASE WHEN Column_Name='A' THEN TheValue ELSE NULL END) AS A, MAX(CASE WHEN ColumnName='B' THEN TheValue ELSE NULL END) AS B

FROM ({Your giant query here}) AS t1

GROUP BY t1.ProductID

or for SQL 2005, you can use the new PIVOT stuff.

SELECT ProductID,A,B

FROM
({Your giant query here}) t1
PIVOT
(
MAX(TheValue)
FOR ColumnName IN
('A','B')
) AS pvt
ORDER BY ProductID

|||

I keep getting Invalid column name 'Column_Name'.

Do I need to set the column name of A and B to the clumns I want displayed?

SELECT t1.ProductID,MAX(CASE WHEN Column_Name='A' THEN TheValue ELSE NULL END) AS A, MAX(CASE WHEN ColumnName='B' THEN TheValue ELSE NULL END) AS B

FROM (Select
PRODUCT_FEATURE_VALUES.PRODUCT_ID AS ProductID,
SHARED_FEATURE_VALUES.Feature_Text_Value As TheValue,
SHARED_FEATURE_TYPES.Feature_Type AS ColumnName
From PRODUCT_FEATURE_VALUES, SHARED_FEATURE_TYPES, SHARED_FEATURE_VALUES
Where
PRODUCT_FEATURE_VALUES.Feature_Type_ID = SHARED_FEATURE_TYPES.Feature_Type_ID And
PRODUCT_FEATURE_VALUES.Feature_Value_ID = SHARED_FEATURE_VALUES.Feature_Value_ID
UNION

Select
EXTENDED_ATTRIBUTE_VALUES.PRODUCT_ID AS ProductID,
ISNULL(small_text_value,large_text_value) AS TheValue,
EXTENDED_ATTRIBUTES.Column_Name AS ColumnName
From EXTENDED_ATTRIBUTE_VALUES, EXTENDED_ATTRIBUTES
Where EXTENDED_ATTRIBUTE_VALUES.Ext_Att_ID = EXTENDED_ATTRIBUTES.Ext_Att_ID) AS t1

GROUP BY t1.ProductID

|||

I got this now and it works good for getting the columns I need. Can I add conditioning for each column after the ColumnName='Value I want as a Column'? Like if I want Test2 As a column, but also only show there Test2 <> 5, where do I add that?

SELECT
t1.ProductID,
MAX(CASE WHEN ColumnName='test1' THEN TheValue ELSE NULL END) AS A,
MAX(CASE WHEN ColumnName='test2' THEN TheValue ELSE NULL END) AS B

FROM (Select
PRODUCT_FEATURE_VALUES.PRODUCT_ID AS ProductID,
SHARED_FEATURE_VALUES.Feature_Text_Value As TheValue,
SHARED_FEATURE_TYPES.Feature_Type AS ColumnName
From PRODUCT_FEATURE_VALUES, SHARED_FEATURE_TYPES, SHARED_FEATURE_VALUES
Where
PRODUCT_FEATURE_VALUES.Feature_Type_ID = SHARED_FEATURE_TYPES.Feature_Type_ID And
PRODUCT_FEATURE_VALUES.Feature_Value_ID = SHARED_FEATURE_VALUES.Feature_Value_ID
UNION

Select
EXTENDED_ATTRIBUTE_VALUES.PRODUCT_ID AS ProductID,
ISNULL(small_text_value,large_text_value) AS TheValue,
EXTENDED_ATTRIBUTES.Column_Name AS ColumnName
From EXTENDED_ATTRIBUTE_VALUES, EXTENDED_ATTRIBUTES
Where EXTENDED_ATTRIBUTE_VALUES.Ext_Att_ID = EXTENDED_ATTRIBUTES.Ext_Att_ID) AS t1

GROUP BY t1.ProductID

|||

I need some more assistance with this since some requirements have changed. Sometimes there will be multiple records with the same columnname, but a distinct value. No matter what I do, its only returning 1 record for each column. I'd like to return all records for each column name and combine them then into one. I dont know if this is possible... In the case base, Military Specification Number is actually in the table 3 times, but this query only grabs the last record of the 3...

SELECT

TOP(100)PERCENT PRODUCT_NUMBER, PRODUCT_NAME,MAX(CASEWHEN ColumnName='Military Specification Number'THEN TheValueELSENULLEND)AS [Military Specification Number]

FROM

(SELECT dbo.PRODUCT_FEATURE_VALUES.PRODUCT_IDAS ProductID, dbo.SHARED_FEATURE_VALUES.FEATURE_TEXT_VALUEAS TheValue,

dbo

.SHARED_FEATURE_TYPES.FEATURE_TYPEAS ColumnName, dbo.PRODUCTS.PRODUCT_NUMBER,

dbo

.PRODUCTS.PRODUCT_NAMEFROM dbo.PRODUCT_FEATURE_VALUESINNERJOIN

dbo

.SHARED_FEATURE_TYPESON

dbo

.PRODUCT_FEATURE_VALUES.FEATURE_TYPE_ID= dbo.SHARED_FEATURE_TYPES.FEATURE_TYPE_IDINNERJOIN

dbo

.SHARED_FEATURE_VALUESON

dbo

.PRODUCT_FEATURE_VALUES.FEATURE_VALUE_ID= dbo.SHARED_FEATURE_VALUES.FEATURE_VALUE_IDINNERJOIN

dbo

.PRODUCTSON dbo.PRODUCT_FEATURE_VALUES.PRODUCT_ID= dbo.PRODUCTS.PRODUCT_IDUNIONALLSELECT dbo.EXTENDED_ATTRIBUTE_VALUES.PRODUCT_IDAS ProductID,ISNULL(dbo.EXTENDED_ATTRIBUTE_VALUES.SMALL_TEXT_VALUE,

dbo

.EXTENDED_ATTRIBUTE_VALUES.LARGE_TEXT_VALUE)AS TheValue, dbo.EXTENDED_ATTRIBUTES.COLUMN_NAMEAS ColumnName,

PRODUCTS_1

.PRODUCT_NUMBER, PRODUCTS_1.PRODUCT_NAMEFROM dbo.EXTENDED_ATTRIBUTE_VALUESINNERJOIN

dbo

.EXTENDED_ATTRIBUTESON

dbo

.EXTENDED_ATTRIBUTE_VALUES.EXT_ATT_ID= dbo.EXTENDED_ATTRIBUTES.EXT_ATT_IDINNERJOIN

dbo

.PRODUCTSAS PRODUCTS_1ON dbo.EXTENDED_ATTRIBUTE_VALUES.PRODUCT_ID= PRODUCTS_1.PRODUCT_ID)AS t1

WHERE

PRODUCT_NUMBER='05048'

GROUP

BY PRODUCT_NUMBER, PRODUCT_NAME

ORDER

BY PRODUCT_NUMBER

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...
>
>

Query Assistance

Hi,
Assuming the following table structure and sample data:
CREATE TABLE TestTab
(Col1 varchar(30) NOT NULL,
Col2 varchar(30) NOT NULL,
Col3 varchar(50) NOT NULL)
Col1 Col2 Col3
XYZ 54 Test
XYZ 54 Simple
ABC 28 Bogus
How can I return the only one entry for a combination of Col1 and Col2?
I.e., Resultset
Col1 Col2 Col3
XYZ 54 Test
ABC 28 Bogus
It doesn't matter wich record is return i.e., Col3 Test or Simple is fine.
Thanks
JerrySELECT col1, col2, MIN(col3)
FROM Test
GROUP BY col1, col2;|||>> How can I return the only one entry for a combination of Col1 and Col2?
You have to specify which row you want to return
It may not matter to the users, but it matters to the DBMS to consistently
derive the resultset. One option would be to simply use an extrema function
on col3 like:
SELECT col1, col2, MAX( col3 )
FROM tbl
GROUP BY col1, col2 ;
Anith|||Duh! Spaced that one. Thanks guys!
Jerry
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1126563751.937497.46640@.g43g2000cwa.googlegroups.com...
> SELECT col1, col2, MIN(col3)
> FROM Test
> GROUP BY col1, col2;
>

Query Assistance

Hi all,
I have three tables:
Table 1:
Amount
InvoiceNumber
Table 2:
TransactionID
InvoiceNumber
Table 3:
Amount
TransactionID
InvoiceNumber
Client
I need to compare the amounts from table 1 and table 3. However I need to
do this by client. This is where the problem arises. Table 1 does not
contain clients, and the invoicenumber amount in Table 1 is a sum of all
transactions that have that InvoiceNumber.
Thus the Invoice Number '500055' could have mulitple clients amounts
included in it in Table 1.
So my thoughts are connect Table 1 to Table 2, this will allow me to get the
individual Transactions (read clients) that are associated with an Invoice
Number. But... If an Invoice number from Table 1 has two TransactionID's in
table 2 I will obviously get a double up... As the amount is coming from
Table 1.
So... My question is this.
How do this comparison? I have no idea and have been headbutting the wall
for a couple of days now.
Thanks!
ClintOn Thu, 10 Nov 2005 09:22:55 +1100, Clint wrote:

>Hi all,
>I have three tables:
>Table 1:
>Amount
>InvoiceNumber
>Table 2:
>TransactionID
>InvoiceNumber
>Table 3:
>Amount
>TransactionID
>InvoiceNumber
>Client
>I need to compare the amounts from table 1 and table 3. However I need to
>do this by client. This is where the problem arises. Table 1 does not
>contain clients, and the invoicenumber amount in Table 1 is a sum of all
>transactions that have that InvoiceNumber.
>Thus the Invoice Number '500055' could have mulitple clients amounts
>included in it in Table 1.
>So my thoughts are connect Table 1 to Table 2, this will allow me to get th
e
>individual Transactions (read clients) that are associated with an Invoice
>Number. But... If an Invoice number from Table 1 has two TransactionID's i
n
>table 2 I will obviously get a double up... As the amount is coming from
>Table 1.
>So... My question is this.
>How do this comparison? I have no idea and have been headbutting the wall
>for a couple of days now.
Hi Clint,
I'm sorry, but I don't really undersatnd what you want. Could you
provide some more information? The info I'd need is:
* CREATE TABLE statements. The description above is too scarce; I want
to know datatypes, keys, and other constraints as well. Complete CREATE
TABLE statements (including all constraints and properties) will give me
the info I need.
* Some sample data to illustrate the problem. Pleasae provide this data
as INSERT statements that I can run (after running the CREATE TABLE
statements) in my test database.
* The expected output, plus an explanation why that is the output you
expect.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||--To get the amounts by Client in table 1:
Select
sum(t1.Amount),
t3.client
from table1 t1
join table3 t3 on t1.invoicenumber = t3.invoicenumber
group by t1.client
--To get the amounts by Client in table 3
Select
sum(t3.Amount),
t3.client
from table1 t1
group by t3.client
--To compare them in one result set:
Select
isnull(t1.client, t3.client) client,
t1.amount as table1Amount,
t3.amount as table3Amount
From
(
Select
sum(t1.Amount) amount,
t3.client
from table1 t1
join table3 t3 on t1.invoicenumber = t3.invoicenumber
group by t1.client
) t1
full outer join
(
Select
sum(t3.Amount) amount,
t3.client
from table1 t1
group by t3.client
) t3 on t1.client = t3.client|||Thanks for your offer, hope this info will assist.
Tables:
CREATE TABLE [dbo].[Table1] (
[InvoiceNum][varchar] (20) COLLATE Latin1_General_CI_AS NOT NULL ,
[AMOUNT] [numeric](28, 12) NOT NULL ,
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Table2] (
[InvoiceNum] [varchar] (20) COLLATE Latin1_General_CI_AS NOT NULL ,
[TRANSID] [varchar] (20) COLLATE Latin1_General_CI_AS NOT NULL ,
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Table3] (
[client] [varchar] (25) COLLATE Latin1_General_CI_AS NOT NULL ,
[TRANSID] [varchar] (20) COLLATE Latin1_General_CI_AS NOT NULL ,
[InvoiceNum] [varchar] (20) COLLATE Latin1_General_CI_AS NOT NULL ,
[AMOUNT] [numeric](28, 12) NOT NULL
) ON [PRIMARY]
Table 1 Data:
INSERT INTO Table1(InvoiceNum, Amount)
VALUES ('Invoice1', '0.3')
go
INSERT INTO Table1(InvoiceNum, Amount)
VALUES ('Invoice1', '0.5')
go
INSERT INTO Table1(InvoiceNum, Amount)
VALUES ('Invoice1', '0.8')
go
INSERT INTO Table1(InvoiceNum, Amount)
VALUES ('Invoice1', '1')
go
INSERT INTO Table1(InvoiceNum, Amount)
VALUES ('Invoice1', '1.5')
go
INSERT INTO Table1(InvoiceNum, Amount)
VALUES ('Invoice1', '7')
Table 2 Data
INSERT INTO Table2(InvoiceNum, TransID)
VALUES ('Invoice1', '1124')
go
INSERT INTO Table2(InvoiceNum, TransID)
VALUES ('Invoice1', '1124')
go
INSERT INTO Table2(InvoiceNum, TransID)
VALUES ('Invoice1', '1111')
go
INSERT INTO Table2(InvoiceNum, TransID)
VALUES ('Invoice1', '1234')
go
INSERT INTO Table2(InvoiceNum, TransID)
VALUES ('Invoice1', '567')
go
INSERT INTO Table2(InvoiceNum, TransID)
VALUES ('Invoice1', '8')
Data Table 3
INSERT INTO table3(InvoiceNum, TransID, Client, Amount)
VALUES ('Invoice1', '1124', 'Bob','2')
go
INSERT INTO table3(InvoiceNum, TransID, Client, Amount)
VALUES ('Invoice1', '1124', 'Jane','.22')
go
INSERT INTO table3(InvoiceNum, TransID, Client, Amount)
VALUES ('Invoice1', '1111', 'Mary','65')
go
INSERT INTO table3(InvoiceNum, TransID, Client, Amount)
VALUES ('Invoice1', '1234', 'Tom','.56')
go
INSERT INTO table3(InvoiceNum, TransID, Client, Amount)
VALUES ('Invoice1', '567', 'Brady','5')
go
INSERT INTO table3(InvoiceNum, TransID, Client, Amount)
VALUES ('Invoice1', '8','Jake','10')
My wanted results are:
For Client = Bob
Invoice, table1amount, table3amount
'Invoice 1','3','7'
This will allow me to start the process into why data is entering one table
but not the other. Essentially my problem is caused by the fact that I dont
have clients in table 1.
Hope this helps.
Clint
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:2lu4n1hkqjm2sj4fv8c8itea7g3ek8oijk@.
4ax.com...
> On Thu, 10 Nov 2005 09:22:55 +1100, Clint wrote:
>
> Hi Clint,
> I'm sorry, but I don't really undersatnd what you want. Could you
> provide some more information? The info I'd need is:
> * CREATE TABLE statements. The description above is too scarce; I want
> to know datatypes, keys, and other constraints as well. Complete CREATE
> TABLE statements (including all constraints and properties) will give me
> the info I need.
> * Some sample data to illustrate the problem. Pleasae provide this data
> as INSERT statements that I can run (after running the CREATE TABLE
> statements) in my test database.
> * The expected output, plus an explanation why that is the output you
> expect.
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)|||On Thu, 10 Nov 2005 11:10:34 +1100, Clint wrote:

>Thanks for your offer, hope this info will assist.
>
(snip CREATE TABLE and INSERT statements)

>My wanted results are:
>For Client = Bob
>Invoice, table1amount, table3amount
>'Invoice 1','3','7'
>This will allow me to start the process into why data is entering one table
>but not the other. Essentially my problem is caused by the fact that I don
t
>have clients in table 1.
>Hope this helps.
Hi Clint,
Thanks for posting the CREATE TABLE and INSERT statements. I was able to
run them smoothly in my test database.
Unfortunately, this didn't help me to understand the logic of your
problem. I've bene looking at your data for some time now, and I've
reread your messages - but I fail to see how the data provided would
lead to the amounts '3' and '7' for Client = Bob.
Maybe you can explain me, step by step, how you get to that data? I can
then attempt to translate that in a corresponding SQL statement.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo,
Thanks!
I must admit my desired result was made up... Using the data that I gave
you.. Client = BOB will have a value of 2.
What I am trying to do is compare table 1's invoices and amounts with the
corresponding values in table 3. However as Table 1 does not have client I
am finding it very difficult to do this.
Quite simply table 1 an invoice number in table 1 could be listed 10 times
with 5 different clients. However seeing how the invoice number is the same
I cannot determine what values are for client bob and what are for client
jane. Obviously I can do this in Table number 3 as the client is listed in
this table.
I apologise for my incorrect results concept. I would using the data I have
provided expect that Bob would have a value of 2 in table 3... but how would
I link this to table 1?
Clint
I really appreciate the assistance Hugo. :)
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:h8g7n1pqpd1er96d7h0ssdqg20ass458is@.
4ax.com...
> On Thu, 10 Nov 2005 11:10:34 +1100, Clint wrote:
>
> (snip CREATE TABLE and INSERT statements)
>
> Hi Clint,
> Thanks for posting the CREATE TABLE and INSERT statements. I was able to
> run them smoothly in my test database.
> Unfortunately, this didn't help me to understand the logic of your
> problem. I've bene looking at your data for some time now, and I've
> reread your messages - but I fail to see how the data provided would
> lead to the amounts '3' and '7' for Client = Bob.
> Maybe you can explain me, step by step, how you get to that data? I can
> then attempt to translate that in a corresponding SQL statement.
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)|||On Fri, 11 Nov 2005 10:23:12 +1100, Clint wrote:

>Hugo,
>Thanks!
>I must admit my desired result was made up... Using the data that I gave
>you.. Client = BOB will have a value of 2.
Hi Clint,
Okay, that clarifies half the problem. The data you originally listed
was '3' for table1 value, and '7' for table3 value. The latter is now
corrected to '2' - which indeed makes a lot more sense.
But how about the other value? The value '3' for table1? I don't see any
row in table1 that holds this value, nor any logical combination of rows
that would help me to arrive at this value.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Ah... yes... that is a sum of three records... 1.5+1+0.5 = 3
So now you can see that one record in table three might be three or more
records in table one.
Thus I need to know how to connect these two tables :)
I am very .
THANKS!
Clint
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:rjn7n19a4vepqnheo3q5rur22b5v760va3@.
4ax.com...
> On Fri, 11 Nov 2005 10:23:12 +1100, Clint wrote:
>
> Hi Clint,
> Okay, that clarifies half the problem. The data you originally listed
> was '3' for table1 value, and '7' for table3 value. The latter is now
> corrected to '2' - which indeed makes a lot more sense.
> But how about the other value? The value '3' for table1? I don't see any
> row in table1 that holds this value, nor any logical combination of rows
> that would help me to arrive at this value.
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)|||On Fri, 11 Nov 2005 12:20:06 +1100, Clint wrote:

>Ah... yes... that is a sum of three records... 1.5+1+0.5 = 3
Hi Clint,
Okay - one step closer to the target. But not quite there yet.
The following six rows are in Table1:
InvoiceNum | Amount
--+--
Invoice1 | 0.3
Invoice1 | 0.5
Invoice1 | 0.8
Invoice1 | 1
Invoice1 | 1.5
Invoice1 | 7
The three rows you want to sum are present - but so are three other
rows, that you (apparently) don't want to sum. Why? How can you tell, bu
looking at the data in this table or in any of the other tables, that
three out of the six rows should be summed? And that it should be
*THESE* three rows, not the rows with value 0.3, 0.8, and 7 ?
This appears to be a specification problem, rather than a query-wriiting
query!
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Exactly. How can I tell. This is the way our ERP system is. This is what
I am after. How do I tell?
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:n61an1t46pcj78goomqocjuu5as5d954q4@.
4ax.com...
> On Fri, 11 Nov 2005 12:20:06 +1100, Clint wrote:
>
> Hi Clint,
> Okay - one step closer to the target. But not quite there yet.
> The following six rows are in Table1:
> InvoiceNum | Amount
> --+--
> Invoice1 | 0.3
> Invoice1 | 0.5
> Invoice1 | 0.8
> Invoice1 | 1
> Invoice1 | 1.5
> Invoice1 | 7
> The three rows you want to sum are present - but so are three other
> rows, that you (apparently) don't want to sum. Why? How can you tell, bu
> looking at the data in this table or in any of the other tables, that
> three out of the six rows should be summed? And that it should be
> *THESE* three rows, not the rows with value 0.3, 0.8, and 7 ?
> This appears to be a specification problem, rather than a query-wriiting
> query!
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)

Query assistance

I am trying to pull some "notes" from a sql database....the notes that
are put into the database come via the web and the user is entering it
for a certain task. they are stored in their own table and field and
get assigned and incremental ID #.

I want to be able to pull up the latest entry to the task, not all of
the notes just the latest one.. The entry does get a timestamp in the
field so I am thinking I might be able to look at that field
somehow... Right now my query shows all notes / entries for the task.

I am an intermediate sql query guy so I hopefully expained enough to
get assistance.

Let me know if you need to know more.Here is the sample data...
iwmsjn_Note iwmsjn_Timestamp
working on SQL queries for reports2/17/2006 4:20:34 PM
Researching a report for Sheri 2/28/2006 4:35:21 PM
Working on Reports / Queries 3/3/2006 3:34:04 PM
Test Delete 3/8/2006 1:45:30 PM

I only want the one that says "Test Delete" stamped for TODAY...not
the others.|||This should do it...

selectiwmsjn_Note
from[tablename] a
whereiwmsjn_Timestamp = (select max(iwmsjn_Timestamp)
from [tablename] b
where a.[ID] = b.[ID])

Jody

Query Assistance

Hi,

I have a need to renumber or resequence the line numbers for each unique claim number. For background, one claim number many contain many line numbers. For each claim number, I need the sequence number to begin at 1 and then increment, until a new claim number is reached, at which point the sequence number goes back to 1. Here's an example of what I want the results to look like:

ClaimNumber LineNumber SequenceNumber
abc123 1 1
abc123 2 2
abc123 3 3
def321 5 1
def321 6 2
ghi456 2 1
jkl789 3 1
jkl789 4 2

So...
SELECT ClaimNumber, LineNumber, <Some Logic> AS SequenceNumber FROM MyTable

Is there any way to do this?

Thanks,
DennisRead the sticky at the top of the forum and give us what it asks for.

Thanks|||CREATE TABLE myTable(ClaimNumber varchar(6), LineNumber int)

INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('abc123',1)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('abc123',2)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('abc123',3)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('def321',5)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('def321',6)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('ghi456',2)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('jkl789',3)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('jkl789',4)



My question: Is it possible to have a calculated field that, in essence renumbers (or auto increments) a particular column based on the value in another column?

Thanks,
Dennis|||To auto increment based on another column, I don't think so.

For this application, maybe a small two column table holding the ClaimNumber and LastLineNumber. As a quick example (not tested)

CREATE TABLE dbo.ClaimLineno (ClaimNo varchar(6) not null, LastLineNo int not null)
GO

ALTER TABLE dbo.ClaimLineno ADD
CONSTRAINT [PK_Claimno] PRIMARY KEY CLUSTERED
(
[ClaimNo]
GO

CREATE PROC ap_GetNextLine @.ClaimNo varchar(6), @.LastLineNumber int OUTPUT
AS

declare @.rcount int

BEGIN TRANSACTION GetNo
SELECT @.LastLineNumber = LastLineNo
FROM dbo.ClaimLineno
WHERE ClaimNo = @.ClaimNo

SELECT @.rcount = @.@.rowcount

IF @.rcount = 1
BEGIN
SELECT @.LastLineNumber = @.LastLineNumber + 1
UPDATE dbo.ClaimLineno
SET LastLineNo = @.LastLineNumber
WHERE ClaimNo = @.ClaimNo
END
ELSE
IF @.rcount = 0
BEGIN
SELECT @.LastLineNumber = 1
INSERT dbo.ClaimLineno (ClaimNo, LastLineNo)
VALUES (@.ClaimNo, @.@.LastLineNumber
END

IF @.rcount in (0,1)
BEGIN
COMMIT
RETURN
END

/*
Code appropriate error handling routine here because your table is screwed up
*/|||To auto increment based on another column, I don't think so.

Can't be DONE!

I don't think so.

USE Northwind
GO

SET NOCOUNT ON
CREATE TABLE myTable(ClaimNumber varchar(6), LineNumber int)
GO

INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('abc123',1)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('abc123',2)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('abc123',3)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('def321',5)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('def321',6)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('ghi456',2)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('jkl789',3)
INSERT INTO myTable(ClaimNumber, LineNumber) VALUES ('jkl789',4)
GO

SELECT * FROM myTable

SELECT a.ClaimNumber, a.LineNumber
, COUNT(b.LineNumber)+1 AS Seq
FROM myTable a
LEFT JOIN myTable b
ON a.ClaimNumber = b.ClaimNumber
AND b.LineNumber < a.LineNumber
GROUP BY a.ClaimNumber, a.LineNumber
ORDER BY a.ClaimNumber, a.LineNumber
GO

SET NOCOUNT OFF
DROP TABLE myTable
GO

query assistance

I have a field in a table that the datatype is varchar
the data stored in the field is a date in the format of 7/19/2007
I need to run a query that will give me all teh records that is of a
certain date or newer.
teh query I am running is
Select * from table1 where {do rec] >= '07/19/2007'
what I get is pretty much everything. items dated 7/31/2006 etc...
how can I run this query correctly?
The reason the field is a varchar is becasue I don't want the 'time' in the
field along with the date.
thanks in advance.
The obvious question is why you stored the values as varchar instead of datetime. I suggest you fix
the design before it causes more trouble, bad performance and grief.
Having said that, you can convert the value to datetime (in the WHERE clause) before you do the
conversion. Since you use a date format which isn't language neutral (assuming the values are stored
in the format m/d/yyyy), you need to use CONVERT (with a proper formatting code) instead of CAST,
and because the conversion of the column value to datetime, you need to be prepared for the query to
be slow. Something like:
WHERE CONVERT(datetime, dtcol, 101) > '20070719'
I suggest you give below some time and thoughts:
http://www.karaszi.com/SQLServer/info_datetime.asp
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:uqVwl3S1HHA.3760@.TK2MSFTNGP03.phx.gbl...
>I have a field in a table that the datatype is varchar
> the data stored in the field is a date in the format of 7/19/2007
> I need to run a query that will give me all teh records that is of a certain date or newer.
> teh query I am running is
> Select * from table1 where {do rec] >= '07/19/2007'
> what I get is pretty much everything. items dated 7/31/2006 etc...
> how can I run this query correctly?
> The reason the field is a varchar is becasue I don't want the 'time' in the field along with the
> date.
>
> thanks in advance.
>
>
|||I tried going to your link, but the page cannot be found
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:A0346BCE-A87B-40A3-9C98-247B6A6B273D@.microsoft.com...
> The obvious question is why you stored the values as varchar instead of
> datetime. I suggest you fix the design before it causes more trouble, bad
> performance and grief.
> Having said that, you can convert the value to datetime (in the WHERE
> clause) before you do the conversion. Since you use a date format which
> isn't language neutral (assuming the values are stored in the format
> m/d/yyyy), you need to use CONVERT (with a proper formatting code) instead
> of CAST, and because the conversion of the column value to datetime, you
> need to be prepared for the query to be slow. Something like:
> WHERE CONVERT(datetime, dtcol, 101) > '20070719'
> I suggest you give below some time and thoughts:
> http://www.karaszi.com/SQLServer/info_datetime.asp
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://sqlblog.com/blogs/tibor_karaszi
>
> "Johnfli" <john@.ivhs.us> wrote in message
> news:uqVwl3S1HHA.3760@.TK2MSFTNGP03.phx.gbl...
>
|||On Aug 2, 12:53 pm, "Johnfli" <j...@.ivhs.us> wrote:
> I have a field in a table that the datatype is varchar
> the data stored in the field is a date in the format of 7/19/2007
> I need to run a query that will give me all teh records that is of a
> certain date or newer.
> teh query I am running is
> Select * from table1 where {do rec] >= '07/19/2007'
> what I get is pretty much everything. items dated 7/31/2006 etc...
> how can I run this query correctly?
> The reason the field is a varchar is becasue I don't want the 'time' in the
> field along with the date.
> thanks in advance.
I do agree that you really should change your database design to use a
proper data type. This will make your life easier and not require
some of the conversions. Storing the time in the database shouldn't
cause you any grief and you shouldn't have any issues with the query
you specified
Of course your workaround will be to utilize the convert function in
your query.
|||Perhaps there was a temporary IP hiccup somewhere. I just re-tried my link and it work fine for me:
http://www.karaszi.com/SQLServer/info_datetime.asp
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:etTzacV1HHA.4344@.TK2MSFTNGP03.phx.gbl...
>I tried going to your link, but the page cannot be found
>
> "Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
> message news:A0346BCE-A87B-40A3-9C98-247B6A6B273D@.microsoft.com...
>
|||I am trying to change the field type to DateTime, but I can not figure out
how.
"acorcoran" <acorcoran@.gmail.com> wrote in message
news:1186105967.168834.62160@.19g2000hsx.googlegrou ps.com...
> On Aug 2, 12:53 pm, "Johnfli" <j...@.ivhs.us> wrote:
> I do agree that you really should change your database design to use a
> proper data type. This will make your life easier and not require
> some of the conversions. Storing the time in the database shouldn't
> cause you any grief and you shouldn't have any issues with the query
> you specified
> Of course your workaround will be to utilize the convert function in
> your query.
>
|||Here's how such a ALTER TABLE statement could look like:
ALTER TABLE tbl
ALTER COLUMN col datetime
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:%23meH$Jf1HHA.3788@.TK2MSFTNGP02.phx.gbl...
>I am trying to change the field type to DateTime, but I can not figure out
> how.
>
>
> "acorcoran" <acorcoran@.gmail.com> wrote in message
> news:1186105967.168834.62160@.19g2000hsx.googlegrou ps.com...
>

query assistance

I have a field in a table that the datatype is varchar
the data stored in the field is a date in the format of 7/19/2007
I need to run a query that will give me all teh records that is of a
certain date or newer.
teh query I am running is
Select * from table1 where {do rec] >= '07/19/2007'
what I get is pretty much everything. items dated 7/31/2006 etc...
how can I run this query correctly?
The reason the field is a varchar is becasue I don't want the 'time' in the
field along with the date.
thanks in advance.The obvious question is why you stored the values as varchar instead of date
time. I suggest you fix
the design before it causes more trouble, bad performance and grief.
Having said that, you can convert the value to datetime (in the WHERE clause
) before you do the
conversion. Since you use a date format which isn't language neutral (assumi
ng the values are stored
in the format m/d/yyyy), you need to use CONVERT (with a proper formatting c
ode) instead of CAST,
and because the conversion of the column value to datetime, you need to be p
repared for the query to
be slow. Something like:
WHERE CONVERT(datetime, dtcol, 101) > '20070719'
I suggest you give below some time and thoughts:
http://www.karaszi.com/SQLServer/info_datetime.asp
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:uqVwl3S1HHA.3760@.TK2MSFTNGP03.phx.gbl...[vbco
l=seagreen]
>I have a field in a table that the datatype is varchar
> the data stored in the field is a date in the format of 7/19/2007
> I need to run a query that will give me all teh records that is of a certa
in date or newer.
> teh query I am running is
> Select * from table1 where {do rec] >= '07/19/2007'
> what I get is pretty much everything. items dated 7/31/2006 etc...
> how can I run this query correctly?
> The reason the field is a varchar is becasue I don't want the 'time' in th
e field along with the
> date.
>
> thanks in advance.
>
>[/vbcol]|||I tried going to your link, but the page cannot be found
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:A0346BCE-A87B-40A3-9C98-247B6A6B273D@.microsoft.com...
> The obvious question is why you stored the values as varchar instead of
> datetime. I suggest you fix the design before it causes more trouble, bad
> performance and grief.
> Having said that, you can convert the value to datetime (in the WHERE
> clause) before you do the conversion. Since you use a date format which
> isn't language neutral (assuming the values are stored in the format
> m/d/yyyy), you need to use CONVERT (with a proper formatting code) instead
> of CAST, and because the conversion of the column value to datetime, you
> need to be prepared for the query to be slow. Something like:
> WHERE CONVERT(datetime, dtcol, 101) > '20070719'
> I suggest you give below some time and thoughts:
> http://www.karaszi.com/SQLServer/info_datetime.asp
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://sqlblog.com/blogs/tibor_karaszi
>
> "Johnfli" <john@.ivhs.us> wrote in message
> news:uqVwl3S1HHA.3760@.TK2MSFTNGP03.phx.gbl...
>|||On Aug 2, 12:53 pm, "Johnfli" <j...@.ivhs.us> wrote:
> I have a field in a table that the datatype is varchar
> the data stored in the field is a date in the format of 7/19/2007
> I need to run a query that will give me all teh records that is of a
> certain date or newer.
> teh query I am running is
> Select * from table1 where {do rec] >= '07/19/2007'
> what I get is pretty much everything. items dated 7/31/2006 etc...
> how can I run this query correctly?
> The reason the field is a varchar is becasue I don't want the 'time' in th
e
> field along with the date.
> thanks in advance.
I do agree that you really should change your database design to use a
proper data type. This will make your life easier and not require
some of the conversions. Storing the time in the database shouldn't
cause you any grief and you shouldn't have any issues with the query
you specified
Of course your workaround will be to utilize the convert function in
your query.|||Perhaps there was a temporary IP hiccup somewhere. I just re-tried my link a
nd it work fine for me:
http://www.karaszi.com/SQLServer/info_datetime.asp
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:etTzacV1HHA.4344@.TK2MSFTNGP03.phx.gbl...[vbco
l=seagreen]
>I tried going to your link, but the page cannot be found
>
> "Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote i
n
> message news:A0346BCE-A87B-40A3-9C98-247B6A6B273D@.microsoft.com...
>[/vbcol]|||I am trying to change the field type to DateTime, but I can not figure out
how.
"acorcoran" <acorcoran@.gmail.com> wrote in message
news:1186105967.168834.62160@.19g2000hsx.googlegroups.com...
> On Aug 2, 12:53 pm, "Johnfli" <j...@.ivhs.us> wrote:
> I do agree that you really should change your database design to use a
> proper data type. This will make your life easier and not require
> some of the conversions. Storing the time in the database shouldn't
> cause you any grief and you shouldn't have any issues with the query
> you specified
> Of course your workaround will be to utilize the convert function in
> your query.
>|||Here's how such a ALTER TABLE statement could look like:
ALTER TABLE tbl
ALTER COLUMN col datetime
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:%23meH$Jf1HHA.3788@.TK2MSFTNGP02.phx.gbl...[vb
col=seagreen]
>I am trying to change the field type to DateTime, but I can not figure out
> how.
>
>
> "acorcoran" <acorcoran@.gmail.com> wrote in message
> news:1186105967.168834.62160@.19g2000hsx.googlegroups.com...
>[/vbcol]

query assistance

I have a field in a table that the datatype is varchar
the data stored in the field is a date in the format of 7/19/2007
I need to run a query that will give me all teh records that is of a
certain date or newer.
teh query I am running is
Select * from table1 where {do rec] >= '07/19/2007'
what I get is pretty much everything. items dated 7/31/2006 etc...
how can I run this query correctly?
The reason the field is a varchar is becasue I don't want the 'time' in the
field along with the date.
thanks in advance.The obvious question is why you stored the values as varchar instead of datetime. I suggest you fix
the design before it causes more trouble, bad performance and grief.
Having said that, you can convert the value to datetime (in the WHERE clause) before you do the
conversion. Since you use a date format which isn't language neutral (assuming the values are stored
in the format m/d/yyyy), you need to use CONVERT (with a proper formatting code) instead of CAST,
and because the conversion of the column value to datetime, you need to be prepared for the query to
be slow. Something like:
WHERE CONVERT(datetime, dtcol, 101) > '20070719'
I suggest you give below some time and thoughts:
http://www.karaszi.com/SQLServer/info_datetime.asp
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:uqVwl3S1HHA.3760@.TK2MSFTNGP03.phx.gbl...
>I have a field in a table that the datatype is varchar
> the data stored in the field is a date in the format of 7/19/2007
> I need to run a query that will give me all teh records that is of a certain date or newer.
> teh query I am running is
> Select * from table1 where {do rec] >= '07/19/2007'
> what I get is pretty much everything. items dated 7/31/2006 etc...
> how can I run this query correctly?
> The reason the field is a varchar is becasue I don't want the 'time' in the field along with the
> date.
>
> thanks in advance.
>
>|||I tried going to your link, but the page cannot be found
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:A0346BCE-A87B-40A3-9C98-247B6A6B273D@.microsoft.com...
> The obvious question is why you stored the values as varchar instead of
> datetime. I suggest you fix the design before it causes more trouble, bad
> performance and grief.
> Having said that, you can convert the value to datetime (in the WHERE
> clause) before you do the conversion. Since you use a date format which
> isn't language neutral (assuming the values are stored in the format
> m/d/yyyy), you need to use CONVERT (with a proper formatting code) instead
> of CAST, and because the conversion of the column value to datetime, you
> need to be prepared for the query to be slow. Something like:
> WHERE CONVERT(datetime, dtcol, 101) > '20070719'
> I suggest you give below some time and thoughts:
> http://www.karaszi.com/SQLServer/info_datetime.asp
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://sqlblog.com/blogs/tibor_karaszi
>
> "Johnfli" <john@.ivhs.us> wrote in message
> news:uqVwl3S1HHA.3760@.TK2MSFTNGP03.phx.gbl...
>>I have a field in a table that the datatype is varchar
>> the data stored in the field is a date in the format of 7/19/2007
>> I need to run a query that will give me all teh records that is of a
>> certain date or newer.
>> teh query I am running is
>> Select * from table1 where {do rec] >= '07/19/2007'
>> what I get is pretty much everything. items dated 7/31/2006 etc...
>> how can I run this query correctly?
>> The reason the field is a varchar is becasue I don't want the 'time' in
>> the field along with the date.
>>
>> thanks in advance.
>>
>|||On Aug 2, 12:53 pm, "Johnfli" <j...@.ivhs.us> wrote:
> I have a field in a table that the datatype is varchar
> the data stored in the field is a date in the format of 7/19/2007
> I need to run a query that will give me all teh records that is of a
> certain date or newer.
> teh query I am running is
> Select * from table1 where {do rec] >= '07/19/2007'
> what I get is pretty much everything. items dated 7/31/2006 etc...
> how can I run this query correctly?
> The reason the field is a varchar is becasue I don't want the 'time' in the
> field along with the date.
> thanks in advance.
I do agree that you really should change your database design to use a
proper data type. This will make your life easier and not require
some of the conversions. Storing the time in the database shouldn't
cause you any grief and you shouldn't have any issues with the query
you specified
Of course your workaround will be to utilize the convert function in
your query.|||Perhaps there was a temporary IP hiccup somewhere. I just re-tried my link and it work fine for me:
http://www.karaszi.com/SQLServer/info_datetime.asp
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:etTzacV1HHA.4344@.TK2MSFTNGP03.phx.gbl...
>I tried going to your link, but the page cannot be found
>
> "Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
> message news:A0346BCE-A87B-40A3-9C98-247B6A6B273D@.microsoft.com...
>> The obvious question is why you stored the values as varchar instead of
>> datetime. I suggest you fix the design before it causes more trouble, bad
>> performance and grief.
>> Having said that, you can convert the value to datetime (in the WHERE
>> clause) before you do the conversion. Since you use a date format which
>> isn't language neutral (assuming the values are stored in the format
>> m/d/yyyy), you need to use CONVERT (with a proper formatting code) instead
>> of CAST, and because the conversion of the column value to datetime, you
>> need to be prepared for the query to be slow. Something like:
>> WHERE CONVERT(datetime, dtcol, 101) > '20070719'
>> I suggest you give below some time and thoughts:
>> http://www.karaszi.com/SQLServer/info_datetime.asp
>> --
>> Tibor Karaszi, SQL Server MVP
>> http://www.karaszi.com/sqlserver/default.asp
>> http://sqlblog.com/blogs/tibor_karaszi
>>
>> "Johnfli" <john@.ivhs.us> wrote in message
>> news:uqVwl3S1HHA.3760@.TK2MSFTNGP03.phx.gbl...
>>I have a field in a table that the datatype is varchar
>> the data stored in the field is a date in the format of 7/19/2007
>> I need to run a query that will give me all teh records that is of a
>> certain date or newer.
>> teh query I am running is
>> Select * from table1 where {do rec] >= '07/19/2007'
>> what I get is pretty much everything. items dated 7/31/2006 etc...
>> how can I run this query correctly?
>> The reason the field is a varchar is becasue I don't want the 'time' in
>> the field along with the date.
>>
>> thanks in advance.
>>
>>
>|||I am trying to change the field type to DateTime, but I can not figure out
how. :(
"acorcoran" <acorcoran@.gmail.com> wrote in message
news:1186105967.168834.62160@.19g2000hsx.googlegroups.com...
> On Aug 2, 12:53 pm, "Johnfli" <j...@.ivhs.us> wrote:
>> I have a field in a table that the datatype is varchar
>> the data stored in the field is a date in the format of 7/19/2007
>> I need to run a query that will give me all teh records that is of a
>> certain date or newer.
>> teh query I am running is
>> Select * from table1 where {do rec] >= '07/19/2007'
>> what I get is pretty much everything. items dated 7/31/2006 etc...
>> how can I run this query correctly?
>> The reason the field is a varchar is becasue I don't want the 'time' in
>> the
>> field along with the date.
>> thanks in advance.
> I do agree that you really should change your database design to use a
> proper data type. This will make your life easier and not require
> some of the conversions. Storing the time in the database shouldn't
> cause you any grief and you shouldn't have any issues with the query
> you specified
> Of course your workaround will be to utilize the convert function in
> your query.
>|||Here's how such a ALTER TABLE statement could look like:
ALTER TABLE tbl
ALTER COLUMN col datetime
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Johnfli" <john@.ivhs.us> wrote in message news:%23meH$Jf1HHA.3788@.TK2MSFTNGP02.phx.gbl...
>I am trying to change the field type to DateTime, but I can not figure out
> how. :(
>
>
> "acorcoran" <acorcoran@.gmail.com> wrote in message
> news:1186105967.168834.62160@.19g2000hsx.googlegroups.com...
>> On Aug 2, 12:53 pm, "Johnfli" <j...@.ivhs.us> wrote:
>> I have a field in a table that the datatype is varchar
>> the data stored in the field is a date in the format of 7/19/2007
>> I need to run a query that will give me all teh records that is of a
>> certain date or newer.
>> teh query I am running is
>> Select * from table1 where {do rec] >= '07/19/2007'
>> what I get is pretty much everything. items dated 7/31/2006 etc...
>> how can I run this query correctly?
>> The reason the field is a varchar is becasue I don't want the 'time' in
>> the
>> field along with the date.
>> thanks in advance.
>> I do agree that you really should change your database design to use a
>> proper data type. This will make your life easier and not require
>> some of the conversions. Storing the time in the database shouldn't
>> cause you any grief and you shouldn't have any issues with the query
>> you specified
>> Of course your workaround will be to utilize the convert function in
>> your query.
>