Showing posts with label date. Show all posts
Showing posts with label date. Show all posts

Friday, March 30, 2012

Finding most recent date?

Hi,
Using query analyzer on a SQL 2000 server. I'm having trouble even
describing what I want here... Let's try this, here's the query:
select distinct pt.patient_id, payer_org_id as 'Payer ID', org.name as
'Payer Description',
pp.plan_name as 'Plan Name', pt_policy.policy_number as 'Policy Number',
Rank, claim_number, posted_transaction_date
from patient as pt
left join pt_policy on pt_policy.patient_id = pt.patient_id
left join organizations as org on org.org_id = pt_policy.payer_org_id
left join payer_plan as pp on pp.sys_id = pt_policy.payer_plan_sys_id
left join chg_item on chg_item.pt_policy_sys_id = pt_policy.sys_id
left join charge_on_claim as coc on coc.chg_item_sys_id = chg_item.sys_id
right join claim on claim.sys_id = coc.claim_sys_id
where pt_policy.discontinued = 'F' and pt.patient_id = '100561'
order by claim_number, pt.patient_id, rank
For each claim_number there are multiple chg_items but I would like to
return just the most recent chg_item based on the posted_transaction_date.
I can't quite figure it out though, I tried a subquery on the where clause
but that reduced it to one item being returned. This query should actually
return 13 records but there are three repeats. Basically I want one record
for each claim_number.
I hope this makes sense and is enough information. Any help is greatly
appreciated.
Thanks in advance,
LinnPlease post a simplified version of table structures, sample data & expected
results. For details refer to: www.aspfaq.com/5006
In general, you can have an approach similar to:
( based on guesswork )
SELECT
FROM claim_tbl t1
WHERE t1._col = ( SELECT TOP 1 t2._col
FROM change_item_tbl t2
WHERE t2.claim_nbr = t1.claim_nbr
ORDER BY posted_transaction_date DESC ) ;
Anith|||you have to use a correlated subquery that has a where clause joining it bac
k
to the main query.
select id, patient, org, a_date
from patient a
where a_date=(select max(a_date) from patient b where b.patient=a.patient)
--
If it aint broke don't brake it.
"Linn Kubler" wrote:

> Hi,
> Using query analyzer on a SQL 2000 server. I'm having trouble even
> describing what I want here... Let's try this, here's the query:
> select distinct pt.patient_id, payer_org_id as 'Payer ID', org.name as
> 'Payer Description',
> pp.plan_name as 'Plan Name', pt_policy.policy_number as 'Policy Number',
> Rank, claim_number, posted_transaction_date
> from patient as pt
> left join pt_policy on pt_policy.patient_id = pt.patient_id
> left join organizations as org on org.org_id = pt_policy.payer_org_id
> left join payer_plan as pp on pp.sys_id = pt_policy.payer_plan_sys_id
> left join chg_item on chg_item.pt_policy_sys_id = pt_policy.sys_id
> left join charge_on_claim as coc on coc.chg_item_sys_id = chg_item.sys_id
> right join claim on claim.sys_id = coc.claim_sys_id
> where pt_policy.discontinued = 'F' and pt.patient_id = '100561'
> order by claim_number, pt.patient_id, rank
> For each claim_number there are multiple chg_items but I would like to
> return just the most recent chg_item based on the posted_transaction_date.
> I can't quite figure it out though, I tried a subquery on the where clause
> but that reduced it to one item being returned. This query should actuall
y
> return 13 records but there are three repeats. Basically I want one recor
d
> for each claim_number.
> I hope this makes sense and is enough information. Any help is greatly
> appreciated.
> Thanks in advance,
> Linn
>
>|||"Anith Sen" <anith@.bizdatasolutions.com> wrote in message
news:eCsxw%23DWGHA.1196@.TK2MSFTNGP03.phx.gbl...
> Please post a simplified version of table structures, sample data &
> expected results. For details refer to: www.aspfaq.com/5006
> In general, you can have an approach similar to:
> ( based on guesswork )
> SELECT
> FROM claim_tbl t1
> WHERE t1._col = ( SELECT TOP 1 t2._col
> FROM change_item_tbl t2
> WHERE t2.claim_nbr = t1.claim_nbr
> ORDER BY posted_transaction_date DESC ) ;
> --
> Anith
>
Thanks much Anith and Joe, both solutions worked once I figured out the
from/join clauses I needed.
For those of you playing along at home, here's what I have at this point:
select distinct claim_number as 'Claim',
RTRIM(pt.last_name) + ', ' + ISNULL(RTRIM(pt.first_name), ' ') AS 'Patient',
payer_org_id as 'Payer ID', org.name as 'Payer Description',
pp.plan_name as 'Plan Name', pt_policy.policy_number as 'Policy Number',
( select min(start_date)
from claim as c1
left join charge_on_claim as coc on coc.claim_sys_id = c1.sys_id
left join chg_item on chg_item.sys_id = coc.chg_item_sys_id
where c1.claim_number = claim.claim_number ) as 'Start Date',
( select max(end_date)
from claim as c1
left join charge_on_claim as coc on coc.claim_sys_id = c1.sys_id
left join chg_item on chg_item.sys_id = coc.chg_item_sys_id
where c1.claim_number = claim.claim_number ) as 'End Date',
( select max(posted_transaction_date)
from claim as c1
left join charge_on_claim as coc on coc.claim_sys_id = c1.sys_id
left join chg_item on chg_item.sys_id = coc.chg_item_sys_id
where c1.claim_number = claim.claim_number ) as 'Transaction Date'
from patient as pt
left join pt_policy on pt_policy.patient_id = pt.patient_id
left join organizations as org on org.org_id = pt_policy.payer_org_id
left join payer_plan as pp on pp.sys_id = pt_policy.payer_plan_sys_id
left join chg_item on chg_item.pt_policy_sys_id = pt_policy.sys_id
left join charge_on_claim as coc on coc.chg_item_sys_id = chg_item.sys_id
right join claim on claim.sys_id = coc.claim_sys_id
where pt_policy.discontinued = 'F'
Once I figured out the posted_transaction_date it was easy to apply it to
two other date fields.
There is only one more wrinkle in my query and that is to total all the
amounts related to each claim. I have successfully compiled another query:
select claim.claim_number, sum(amount) as 'Claim Balance'
from claim
left join ar_detail on ar_detail.claim_sys_id = claim.sys_id
group by claim.claim_number
order by claim.claim_number
But my attempts to introduce this directly into the above query have so far
been unsuccessfull. If I make these queries into views I can easily combine
them but I'm suspecting there is a more elegant solution. My problem is
that this is a purchased database product and I'm not allowed to add my own
views or tables to the DB. So I'm using either Visual FoxPro or Excel to
build these reports.
I tried following the etiquette rules you referenced Anith but I prefer
making timely responses to follow up posts and with all the one-to-many
relations in this query I'll be assembling adequate sample data for a w.
I'll start working on it but if you have any suggestions based on what I've
already provided I'm willing to give them a try.
I thought it was possible to do a subquery in a join statement but I can't
figure out the syntax. Now that I write that I don't think that's the
correct approach anyways. When I added it to the fields list, similar to
the date fields, it simply totalled up all of the amounts instead of total
by claim number. Any suggestions are welcome.
Thanks again,
Linn

finding max date

I am not sure how to phrase this query...if i could have MAX in my
where clause it would be:
SELECT jj.id, jj.lastname, jj.firstname, jj.StartDt, jj.TotalDays,
sum(jpm.NbrDaysPaidFor) AS DaysPaidFor, sum(jpm.Amount) AS TotalPaid
FROM table1 jj
inner join table2 jp on jj.id = jp.id
inner join table3 jpm on jp.payeeid = jpm.payeeid
inner join table4 jpc on jpm.paychecknbr = jpc.paychecknbr
inner join table5 jt on jpc.trid = jt.trid
where (jj.enddt BETWEEN @.StartDt AND @.EndDt)
AND (max(jt.verifieddt) BETWEEN @.StartDt AND @.EndDt)
I need to get the MAX verifieddt and then check to see if it is between
the startdt and enddt passed. Can someone help?
Thank you!*untested*
SELECT jj.id, jj.lastname, jj.firstname, jj.StartDt, jj.TotalDays,
sum(jpm.NbrDaysPaidFor) AS DaysPaidFor, sum(jpm.Amount) AS TotalPaid
FROM table1 jj
inner join table2 jp on jj.id = jp.id
inner join table3 jpm on jp.payeeid = jpm.payeeid
inner join table4 jpc on jpm.paychecknbr = jpc.paychecknbr
inner join table5 jt on jpc.trid = jt.trid
where (jj.enddt BETWEEN @.StartDt AND @.EndDt)
group by jj.id, jj.lastname, jj.firstname, jj.StartDt, jj.TotalDays
having (max(jt.verifieddt) BETWEEN @.StartDt AND @.EndDt)|||I did forget my group by statement b/c I left out the rest of my where
for ease of reading. I probably should have just put the whole thing
up here...when I tried 'having', I got an error that the column was
invalid in the having b/c it is not contained in either an aggregate
function or the group by clause.
so, here's the whole hairy mess:
SELECT t1.id, t1.lastname, t1.firstname, t1.startdt, t1.totaldays,
sum(t3.NbrDaysPaidFor) AS DaysPaidFor, sum(t3.Amount) AS TotalPaid
FROM table1 t1
inner join table2 t2 on t1.id = t2.id
inner join table3 t3 on t2.payeeid = t3.payeeid
inner join table4 t4 on t3.paychecknbr = t4.paychecknbr
inner join table5 t5 on t4.trid = t5.trid
where t1.totaldays > 1
AND t1.statuscode = 'PF'
AND t3.StatusCode = 'VE'
GROUP BY t1.id, t1.lastname, t1.firstname, t1.startdt, t1.totaldays
having (((((t1.enddt BETWEEN @.StartDt AND @.EndDt) AND
(max(t5.verifieddt) BETWEEN @.StartDt AND @.EndDt))
OR (t1.enddt < @.StartDt AND max(t5.verifieddt) BETWEEN @.StartDt AND
@.EndDt))
AND t4.statuscode IN (SELECT code FROM table6 WHERE codetype =
'status'
AND (code = 'GO' OR code = 'GP')))
OR (max(t5.verifieddt) < @.StartDt AND (t4.VoidDt BETWEEN @.StartDt AND
@.EndDt)))|||When I run your query I get the 'column invalid in HAVING clause' error on
t1.enddt, t4.statuscode and t4.voiddt. Since you are already grouping on
t1.id, I would say that it is safe to also group on t1.enddt. Throw that
into your GROUP BY clause and now you just have t4 to worry about.
I'm not sure about this bit:
max(t5.verifieddt) < @.StartDt AND t4.VoidDt BETWEEN @.StartDt AND @.EndDt
Which t4.VoidDt value are you talking about here? Are you expecting several
t4 rows for each t1 row? (it looks like it).
In English, is this line trying to say "where 'the maximum value of
t5.verifieddt on those rows whose corresponding t4.voiddt is between
@.startDt and @.endDt' is less than @.startDt"?
"Confused" <cschanz@.gmail.com> wrote in message
news:1138386931.324271.157020@.f14g2000cwb.googlegroups.com...
>I did forget my group by statement b/c I left out the rest of my where
> for ease of reading. I probably should have just put the whole thing
> up here...when I tried 'having', I got an error that the column was
> invalid in the having b/c it is not contained in either an aggregate
> function or the group by clause.
> so, here's the whole hairy mess:
> SELECT t1.id, t1.lastname, t1.firstname, t1.startdt, t1.totaldays,
> sum(t3.NbrDaysPaidFor) AS DaysPaidFor, sum(t3.Amount) AS TotalPaid
> FROM table1 t1
> inner join table2 t2 on t1.id = t2.id
> inner join table3 t3 on t2.payeeid = t3.payeeid
> inner join table4 t4 on t3.paychecknbr = t4.paychecknbr
> inner join table5 t5 on t4.trid = t5.trid
> where t1.totaldays > 1
> AND t1.statuscode = 'PF'
> AND t3.StatusCode = 'VE'
> GROUP BY t1.id, t1.lastname, t1.firstname, t1.startdt, t1.totaldays
> having (((((t1.enddt BETWEEN @.StartDt AND @.EndDt) AND
> (max(t5.verifieddt) BETWEEN @.StartDt AND @.EndDt))
> OR (t1.enddt < @.StartDt AND max(t5.verifieddt) BETWEEN @.StartDt AND
> @.EndDt))
> AND t4.statuscode IN (SELECT code FROM table6 WHERE codetype =
> 'status'
> AND (code = 'GO' OR code = 'GP')))
> OR (max(t5.verifieddt) < @.StartDt AND (t4.VoidDt BETWEEN @.StartDt AND
> @.EndDt)))
>|||> In English, is this line trying to say "where 'the maximum value of
> t5.verifieddt on those rows whose corresponding t4.voiddt is between
> @.startDt and @.endDt' is less than @.startDt"?
Eek, word problems, which I always detested.
"Confused", please see http://www.aspfaq.com/5006 ... this way, you can
provide us proper specs, we can give a tested and working solution, and end
this madness.
A

Thursday, March 29, 2012

finding first record ... !?

I have a table as follows:

- user_id (key)
- user_email_address (text)
- user_request_date (text)
- user_sent_date (time/date)

An automated macro will run every 5 minutes and needs to run a SQL UPDATE
that:

- finds the FIRST (ONE ROW ONLY) (youngest) record where
- user_request_date is the most recent
- AND user_sent_date is NULL (i.e. blank)

- THEN UPDATES the user_sent_date for THAT record to NOW() (i.e. the
current system date/time)

For example:

- record 33 - request_date 01-JUL-03 14:55:03 - user_sent_date = NULL
- record 34 - request_date 01-JUL-03 15:03:46 - user_sent_date = NULL
- record 35 - request_date 01-JUL-03 16:08:08 - user_sent_date = NULL
- record 36 - request_date 01-JUL-03 16:57:31 - user_sent_date = NULL
- record 37 - request_date 01-JUL-03 17:11:41 - user_sent_date = NULL

SO - the above NEEDED SQL UPDATE would update ONLY row 33 (the FIRST ROW)

- update record 33 - with NOW() time and date
THEN record 34, then 35, then 36, then 37
ONE ROW at a time per each SQL UPDATE

Any ideas!?
Thanks!
Richard

richard @. rcbuchanan . comRichard,

Try something like

update Richard set
user_sent_date = getdate()
where user_id = (
select top 1 user_id from Richard R
where R.user_sent_date is null
order by user_request_date
)

Your narrative and your example don't agree on whether
you want the most recent (youngest), or least recent (oldest)
user_request_date, so you may need to add DESC to the
order by clause.

Steve Kass
Drew University

Richard C Buchanan wrote:

>I have a table as follows:
>- user_id (key)
>- user_email_address (text)
>- user_request_date (text)
>- user_sent_date (time/date)
>An automated macro will run every 5 minutes and needs to run a SQL UPDATE
>that:
>- finds the FIRST (ONE ROW ONLY) (youngest) record where
> - user_request_date is the most recent
> - AND user_sent_date is NULL (i.e. blank)
> - THEN UPDATES the user_sent_date for THAT record to NOW() (i.e. the
>current system date/time)
>
>For example:
>- record 33 - request_date 01-JUL-03 14:55:03 - user_sent_date = NULL
>- record 34 - request_date 01-JUL-03 15:03:46 - user_sent_date = NULL
>- record 35 - request_date 01-JUL-03 16:08:08 - user_sent_date = NULL
>- record 36 - request_date 01-JUL-03 16:57:31 - user_sent_date = NULL
>- record 37 - request_date 01-JUL-03 17:11:41 - user_sent_date = NULL
>SO - the above NEEDED SQL UPDATE would update ONLY row 33 (the FIRST ROW)
>- update record 33 - with NOW() time and date
>THEN record 34, then 35, then 36, then 37
>ONE ROW at a time per each SQL UPDATE
>
>Any ideas!?
>Thanks!
>Richard
>richard @. rcbuchanan . com
>

Finding End of Month

Does anyone have a VB function they could pass along for
converting a date to the end of the last month?
I have a report that will be run for the period ending the prior
month and want the parameter date to default as follows:
Assum they are running it on 12/21, date should default to 11/30/2005
Thanks!"Mike Harbinger" <MikeH@.Cybervillage.net> wrote in news:u#uZqUnBGHA.516
@.TK2MSFTNGP15.phx.gbl:
> Does anyone have a VB function they could pass along for
> converting a date to the end of the last month?
> I have a report that will be run for the period ending the prior
> month and want the parameter date to default as follows:
> Assum they are running it on 12/21, date should default to 11/30/2005
> Thanks!
>
>
DateAdd(DateInterval.Day, (DatePart(DateInterval.Day, Now)) * -1, Now)|||Outstanding, many thanks!
"Asher_N" <compguy666@.hotmail.com> wrote in message
news:Xns9733AA89568F9compguy666hotmailcom@.207.46.248.16...
> "Mike Harbinger" <MikeH@.Cybervillage.net> wrote in news:u#uZqUnBGHA.516
> @.TK2MSFTNGP15.phx.gbl:
>> Does anyone have a VB function they could pass along for
>> converting a date to the end of the last month?
>> I have a report that will be run for the period ending the prior
>> month and want the parameter date to default as follows:
>> Assum they are running it on 12/21, date should default to 11/30/2005
>> Thanks!
>>
> DateAdd(DateInterval.Day, (DatePart(DateInterval.Day, Now)) * -1, Now)|||Asher
I am using timedate format; can it be set to the end of the month 11:59 pm?
"Asher_N" <compguy666@.hotmail.com> wrote in message
news:Xns9733AA89568F9compguy666hotmailcom@.207.46.248.16...
> "Mike Harbinger" <MikeH@.Cybervillage.net> wrote in news:u#uZqUnBGHA.516
> @.TK2MSFTNGP15.phx.gbl:
>> Does anyone have a VB function they could pass along for
>> converting a date to the end of the last month?
>> I have a report that will be run for the period ending the prior
>> month and want the parameter date to default as follows:
>> Assum they are running it on 12/21, date should default to 11/30/2005
>> Thanks!
>>
> DateAdd(DateInterval.Day, (DatePart(DateInterval.Day, Now)) * -1, Now)|||If your using 2005, you use my misc date project at
http://channel9.msdn.com/ShowPost.aspx?PostID=147390
Then use GetEndOfMonth(DateTime) UDF. This gives you the last day and
hour:minute:second:millisecond of that day (i.e. adding one more ms would
move the date to start of next day.)
--
William Stacey [MVP]
"Mike Harbinger" <MikeH@.Cybervillage.net> wrote in message
news:%235%236n4nBGHA.216@.TK2MSFTNGP15.phx.gbl...
> Asher
> I am using timedate format; can it be set to the end of the month 11:59
> pm?
> "Asher_N" <compguy666@.hotmail.com> wrote in message
> news:Xns9733AA89568F9compguy666hotmailcom@.207.46.248.16...
>> "Mike Harbinger" <MikeH@.Cybervillage.net> wrote in news:u#uZqUnBGHA.516
>> @.TK2MSFTNGP15.phx.gbl:
>> Does anyone have a VB function they could pass along for
>> converting a date to the end of the last month?
>> I have a report that will be run for the period ending the prior
>> month and want the parameter date to default as follows:
>> Assum they are running it on 12/21, date should default to 11/30/2005
>> Thanks!
>>
>>
>> DateAdd(DateInterval.Day, (DatePart(DateInterval.Day, Now)) * -1, Now)
>|||William
Thanks for your reply but I an still on RS 2000
"William Stacey [MVP]" <william.stacey@.gmail.com> wrote in message
news:eNviqHpBGHA.3896@.TK2MSFTNGP09.phx.gbl...
> If your using 2005, you use my misc date project at
> http://channel9.msdn.com/ShowPost.aspx?PostID=147390
> Then use GetEndOfMonth(DateTime) UDF. This gives you the last day and
> hour:minute:second:millisecond of that day (i.e. adding one more ms would
> move the date to start of next day.)
> --
> William Stacey [MVP]
> "Mike Harbinger" <MikeH@.Cybervillage.net> wrote in message
> news:%235%236n4nBGHA.216@.TK2MSFTNGP15.phx.gbl...
>> Asher
>> I am using timedate format; can it be set to the end of the month 11:59
>> pm?
>> "Asher_N" <compguy666@.hotmail.com> wrote in message
>> news:Xns9733AA89568F9compguy666hotmailcom@.207.46.248.16...
>> "Mike Harbinger" <MikeH@.Cybervillage.net> wrote in news:u#uZqUnBGHA.516
>> @.TK2MSFTNGP15.phx.gbl:
>> Does anyone have a VB function they could pass along for
>> converting a date to the end of the last month?
>> I have a report that will be run for the period ending the prior
>> month and want the parameter date to default as follows:
>> Assum they are running it on 12/21, date should default to 11/30/2005
>> Thanks!
>>
>>
>> DateAdd(DateInterval.Day, (DatePart(DateInterval.Day, Now)) * -1, Now)
>>
>|||I missed the VB function need. Here is a c# method you can convert:
public static DateTime GetEndOfMonth(DateTime date)
{
int daysInMonth = DateTime.DaysInMonth(date.Year, date.Month);
return new DateTime(date.Year, date.Month, daysInMonth, 23, 59,
59, 999);
}
private void button9_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Parse("12/22/2005"); // Any date.
DateTime lastMth = date.AddMonths(-1);
DateTime endOfLast = GetEndOfMonth(lastMth);
Console.WriteLine("End of Last Month:" + endOfLast);
}
--
William Stacey [MVP]
"Mike Harbinger" <MikeH@.Cybervillage.net> wrote in message
news:unxvFipBGHA.3496@.TK2MSFTNGP11.phx.gbl...
> William
> Thanks for your reply but I an still on RS 2000
> "William Stacey [MVP]" <william.stacey@.gmail.com> wrote in message
> news:eNviqHpBGHA.3896@.TK2MSFTNGP09.phx.gbl...
>> If your using 2005, you use my misc date project at
>> http://channel9.msdn.com/ShowPost.aspx?PostID=147390
>> Then use GetEndOfMonth(DateTime) UDF. This gives you the last day and
>> hour:minute:second:millisecond of that day (i.e. adding one more ms would
>> move the date to start of next day.)
>> --
>> William Stacey [MVP]
>> "Mike Harbinger" <MikeH@.Cybervillage.net> wrote in message
>> news:%235%236n4nBGHA.216@.TK2MSFTNGP15.phx.gbl...
>> Asher
>> I am using timedate format; can it be set to the end of the month 11:59
>> pm?
>> "Asher_N" <compguy666@.hotmail.com> wrote in message
>> news:Xns9733AA89568F9compguy666hotmailcom@.207.46.248.16...
>> "Mike Harbinger" <MikeH@.Cybervillage.net> wrote in news:u#uZqUnBGHA.516
>> @.TK2MSFTNGP15.phx.gbl:
>> Does anyone have a VB function they could pass along for
>> converting a date to the end of the last month?
>> I have a report that will be run for the period ending the prior
>> month and want the parameter date to default as follows:
>> Assum they are running it on 12/21, date should default to 11/30/2005
>> Thanks!
>>
>>
>> DateAdd(DateInterval.Day, (DatePart(DateInterval.Day, Now)) * -1, Now)
>>
>>
>

Wednesday, March 28, 2012

Finding due date from a six character long date field

Hi All,
Here is my problem.
I have a datefield as varchar and six characters long.
The date is shown as 200102 which means the entire month of February
in 2001.
I need to find the due date based on this adding 30 days and the date
will be the last date of the month.
For ex.
if the bill date is 200102 the due date will be 03/30/2001
if the bill date is 200112 the due date will be 01/31/2002
and so on.
Could anyone please tell me how can I write the query?
I have given the DDLs below:
CREATE TABLE [dbo].[Table1] (
[ClaimNumber] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[VENDORCDE] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[INVOICENO] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
[SUPLBILLDT] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
,
)
Insert into Table1(ClaimNumber, VENDORCDE, INVOICENO, SUPLBILLDT)
values('K123', 'BGZ12', '500001', '200101')
Insert into Table1(ClaimNumber, VENDORCDE, INVOICENO, SUPLBILLDT)
values('K123', 'BGZ12', '500001', '200102')
Insert into Table1(ClaimNumber, VENDORCDE, INVOICENO, SUPLBILLDT)
values('K123', 'BGZ12', '500001', '200103')
Insert into Table1(ClaimNumber, VENDORCDE, INVOICENO, SUPLBILLDT)
values('K123', 'BGZ12', '500001', '200112')
I was trying to run the following query:
SELECT *, dateadd(day, 30, SUPLBILLDT)AS DueDate FROMTable1 where
INVOICENO='500004'
of course, that did not give me the right answer.
I do highly appreciate your help.
Thanks a million in advance.
Best regards,
mamunHello Magmun !
Try this:
--German Version with dot seperated
Select dateadd(d,-1,dateadd(m,2,('01.' + right(SUPLBILLDT,2) + '.' +
left(SUPLBILLDT,4)))) from Table1
--English Version with commy separated
Select dateadd(d,-1,dateadd(m,2,(right(SUPLBILLDT,2) + '/01/' +
left(SUPLBILLDT,4)))) from Table1
HTH, Jens Süßmeyer.|||How about
SELECT due_date = DATEADD
(
MONTH,
2,
CONVERT(SMALLDATETIME, bill_date + '01', 112)
)-1
FROM table
(I assume you meant 03/31/2001, since 03/30 is not the last day of March.
And also, you're not adding 30 days to 20011201 and then setting the due
date to be the last day of that month, because 20011201 + 30 = 20011231 and
the last day of that month is 12/31, not 20020131. In other words, the
description of your requirements does not match your sample output... so if
the above query doesn't do what you want, you'll need to clarify;
preferably, with actual table structure, sample data (in the form of a
functional insert statement), and desired results.)
"Mamun" <mamun_ah@.hotmail.com> wrote in message
news:6012e7ab.0308220710.1ed91260@.posting.google.com...
> Hi All,
> Here is my problem.
> I have a datefield as varchar and six characters long.
> The date is shown as 200102 which means the entire month of February
> in 2001.
> I need to find the due date based on this adding 30 days and the date
> will be the last date of the month.
> For ex.
> if the bill date is 200102 the due date will be 03/30/2001
> if the bill date is 200112 the due date will be 01/31/2002
> and so on.
> Could anyone please tell me how can I write the query?
>
> I have given the DDLs below:
>
>
> CREATE TABLE [dbo].[Table1] (
> [ClaimNumber] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [VENDORCDE] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [INVOICENO] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> [SUPLBILLDT] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ,
> )
>
> Insert into Table1(ClaimNumber, VENDORCDE, INVOICENO, SUPLBILLDT)
> values('K123', 'BGZ12', '500001', '200101')
> Insert into Table1(ClaimNumber, VENDORCDE, INVOICENO, SUPLBILLDT)
> values('K123', 'BGZ12', '500001', '200102')
> Insert into Table1(ClaimNumber, VENDORCDE, INVOICENO, SUPLBILLDT)
> values('K123', 'BGZ12', '500001', '200103')
> Insert into Table1(ClaimNumber, VENDORCDE, INVOICENO, SUPLBILLDT)
> values('K123', 'BGZ12', '500001', '200112')
> I was trying to run the following query:
> SELECT *, dateadd(day, 30, SUPLBILLDT)AS DueDate FROMTable1 where
> INVOICENO='500004'
> of course, that did not give me the right answer.
> I do highly appreciate your help.
> Thanks a million in advance.
> Best regards,
> mamun|||Why not return as a datetime, then you can wrap whatever presentation you
want around it using CONVERT and style. In your method, btw, you are
assuming that all of your string concatenations will not break datetime; I'm
not sure this is a healthy assumption, since you may not want to write code
that relies on a specific language / dateformat setting, and the machine's
regional settings.
"Jens Süßmeyer" <jsuessmeyer@.[REJECT_SPAM]web.de> wrote in message
news:eM$OtKMaDHA.2668@.TK2MSFTNGP09.phx.gbl...
> Hello Magmun !
> Try this:
>
> --German Version with dot seperated
> Select dateadd(d,-1,dateadd(m,2,('01.' + right(SUPLBILLDT,2) + '.' +
> left(SUPLBILLDT,4)))) from Table1
> --English Version with commy separated
> Select dateadd(d,-1,dateadd(m,2,(right(SUPLBILLDT,2) + '/01/' +
> left(SUPLBILLDT,4)))) from Table1
>
> HTH, Jens Süßmeyer.
>|||OK, convinced :)). Didn´t thought about this solution, even we use it
(Yours, just implemented by ME) to keep track of our guarantee expiry dates
X-)).
Jens Süßmeyer.sql

Finding designation of an employee on a given date

Hi all,

I have two tables

CREATE TABLE [JEMP] (
[EMPID] [int] NOT NULL ,
[DESIGID] [int] NULL , -- CURRENT DESIGNATION OF EMPLOYEE
[DOB] [smalldatetime] NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [JPRO] (
[PromoID] [int] IDENTITY (1, 1) NOT NULL ,
[EmpID] [int] NOT NULL ,
[EffectiveDate] [smalldatetime] NOT NULL ,
[NewDesigID] [int] NOT NULL , -- PROMOTED TO DESIGNATION
[DesigID] [int] NULL -- PROMOTED FROM DESIGNATION
) ON [PRIMARY]
GO

INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(1,1,'1962-03-11 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(2,25,'1980-10-7 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(3,8,'1978-04-05 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(4,7,'1962-07-12 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(5,22,'1973-02-12 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(6,55,'1971-02-12 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(7,11,'1973-09-12 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(8,22,'1975-02-12 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(9,22,'1977-02-12 00:00:00')
INSERT INTO JEMP(EMPID,DESIGID,DOB) VALUES(10,23,'1984-07-11 00:00:00')

INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(3,'2002-15-11 00:00:00',7,20)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(3,'2003-03-01 00:00:00',8,7)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(4,'2002-01-04 00:00:00',20,22)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(4,'2005-05-01 00:00:00',7,20)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(5,'2001-10-01 00:00:00',22,23)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(6,'2001-08-01 00:00:00',55,NULL)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(7,'2003-10-01 00:00:00',11,8)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(8,'2001-09-01 00:00:00',22,23)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(9,'2002-01-05 00:00:00',22,23)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(10,'2002-11-01 00:00:00',24,25)
INSERT INTO JPRO(EmpID,EffectiveDate,NewDesigID,DesigID)
VALUES(10,'2003-11-15 00:00:00',23,24)

--
I wish to find the designation of employee on given date by using
promotion and master table . I am using the following query to get the
result

select isnull( ( select top 1 newdesigid from JPRO where
empid=1 and effectivedate<'anygivendate' order by effectivedate desc )
, (select desigid from empmast where empid=1) )

It did give the result but looking for better method to solve this.

With regards
JatinderHistory is usually modeled in durations with a (start_time, end_time)
pair; this lets you use a BETWEEN predicate for most of your queries.|||jsfromynr (jatinder.singh@.clovertechnologies.com) writes:
> I wish to find the designation of employee on given date by using
> promotion and master table . I am using the following query to get the
> result
> select isnull( ( select top 1 newdesigid from JPRO where
> empid=1 and effectivedate<'anygivendate' order by effectivedate desc )
> , (select desigid from empmast where empid=1) )
>
> It did give the result but looking for better method to solve this.

I don't see anything seriously wrong with that query. Here is an
alternate:

select Top 1 NewDesigID
from (select NewDesigID, EffectiveDate
from JPRO
where EmpID=7 and
EffectiveDate < '20050301'
union
select DESIGID, '19000101'
from JEMP
where EMPID=7) AS x
order by EffectiveDate desc

But I'm not sure in what way it would be "better".

If you are looking for a more ANSI way of doing it, you would have
to get the MAX(EffectiveDate) and then join back to the derived
table again. As you may guess, this is likely to be less effecient.
In SQL 2005, you could use a CTE (Common Table Expresssion) to avoid
repetition of the code for the derived table, but alas the query
plan is likely to be equally ineffecient.

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

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

Finding date using PATINDEX in varchar

Hi:
One of the columns in my table is a notes column i.e everytime a user
updates it the date,time, users name and his/her note gets appended in
front. The notes column has text in following format:
8/4/2006-9:46:37 AM-Linda King-Per MDCR no clm on file,reblld.
5/4/2006-9:19:09 AM-Jenny Hopins-MEDICARE PAID $11.37 FOR 3/22.
I am supposed to filter out the data by each user,its date and time i.e
8/4/2006 Linda King Per MDCR no clm on file,reblld.
5/4/2006 Jenny Hopins MEDICARE PAID $11.37 FOR 3/22.
Any suggestions are welcomed.Hi
DECLARE @.st VARCHAR(100)
SET @.st='8/4/2006-9:46:37 AM-Linda King-Per MDCR no clm on file,reblld'
SELECT
SUBSTRING(SUBSTRING(@.st,1,CHARINDEX(' ',@.st)),1,
CHARINDEX('-',SUBSTRING(@.st,1,CHARINDEX(' ',@.st)))-1)+
SUBSTRING(@.st,CHARINDEX(' ',@.st),LEN(@.st))
<sfazili@.gmail.com> wrote in message
news:1155574594.397976.247140@.75g2000cwc.googlegroups.com...
> Hi:
> One of the columns in my table is a notes column i.e everytime a user
> updates it the date,time, users name and his/her note gets appended in
> front. The notes column has text in following format:
> 8/4/2006-9:46:37 AM-Linda King-Per MDCR no clm on file,reblld.
> 5/4/2006-9:19:09 AM-Jenny Hopins-MEDICARE PAID $11.37 FOR 3/22.
> I am supposed to filter out the data by each user,its date and time i.e
> 8/4/2006 Linda King Per MDCR no clm on file,reblld.
> 5/4/2006 Jenny Hopins MEDICARE PAID $11.37 FOR 3/22.
> Any suggestions are welcomed.
>|||Hi Uri:
Thanks for ur reply. Actually the notes field has text in the follwoing
format:
8/4/2006-9:46:37 AM-Linda King-Per MDCR/ no clm on file,reblld
5/4/2006-9:19:09 AM-Jenny Hopins-MEDICARE PAID $11.37 FOR 3/22
3/30/2006-10:23:09 AM-Maria James-Patient asks to follow -MEDICARE
Each update to the notes field just get appended to the field in front.
Firstly, I need to separate each individual update..cant use space as
an identifier... need help here. The thing is that after each
indiviaudal note is identified it should be in follwoing format:
8/4/2006-9:46:37 AM-Linda King-Per MDCR/ no clm on file,reblld
5/4/2006-9:19:09 AM-Jenny Hopins-MEDICARE PAID $11.37 FOR 3/22
3/30/2006-10:23:09 AM-Maria James-Patient asks to follow -MEDICARE
After this need to separate each individaul note into thre columns:
8/4/2006 Linda King Per MDCR/ no clm on file,reblld
5/4/2006 Jenny Hopins MEDICARE PAID $11.37 FOR 3/22
3/30/2006 Maria James Patient asks to follow -MEDICARE
Any suggestions appreciated
Uri Dimant wrote:
> Hi
> DECLARE @.st VARCHAR(100)
> SET @.st='8/4/2006-9:46:37 AM-Linda King-Per MDCR no clm on file,reblld'
> SELECT
> SUBSTRING(SUBSTRING(@.st,1,CHARINDEX(' ',@.st)),1,
> CHARINDEX('-',SUBSTRING(@.st,1,CHARINDEX(' ',@.st)))-1)+
> SUBSTRING(@.st,CHARINDEX(' ',@.st),LEN(@.st))
>
>
> <sfazili@.gmail.com> wrote in message
> news:1155574594.397976.247140@.75g2000cwc.googlegroups.com...
> > Hi:
> >
> > One of the columns in my table is a notes column i.e everytime a user
> > updates it the date,time, users name and his/her note gets appended in
> > front. The notes column has text in following format:
> >
> > 8/4/2006-9:46:37 AM-Linda King-Per MDCR no clm on file,reblld.
> > 5/4/2006-9:19:09 AM-Jenny Hopins-MEDICARE PAID $11.37 FOR 3/22.
> >
> > I am supposed to filter out the data by each user,its date and time i.e
> > 8/4/2006 Linda King Per MDCR no clm on file,reblld.
> > 5/4/2006 Jenny Hopins MEDICARE PAID $11.37 FOR 3/22.
> >
> > Any suggestions are welcomed.
> >

Finding date clashes

If I had a table of holidayItems (a holiday is made up of one or more
holidayItems) that contains the columns, Id, HolidayID, StartDate EndDate,
and I wanted to write a sproc that returned a table of clashes i.e the
Holiday ID,the Id of the holiday it clashed with and the dates the holidays
clash. How would I go about it? There will be no clashes of holiday item
dates within a holiday. I am looking for clashes between different holidays.
Sample data:
ID HolidayID StartDate EndDate
1 1 08/05/05 08/10/05
2 1 08/13/05 08/15/05
3 2 08/01/05 08/05/05
4 3 08/02/05 08/04/05
5 4 08/13/05 08/20/05
6 4 08/23/05 08/25/05
Result set
HolidayID ClashesWithHolidayID DateClash
1 2 08/05/05
1 4 08/13/05
1 4 08/14/05
1 4 08/15/05
2 3 08/02/05
2 3 08/03/05
2 3 08/04/05
Table script
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[HolidayItem]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[HolidayItem]
GO
CREATE TABLE [dbo].[HolidayItem] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[HolidayID] [int] NOT NULL ,
[StartDate] [smalldatetime] NOT NULL ,
[EndDate] [smalldatetime] NOT NULL
) ON [PRIMARY]
GOSELECT H1.id, H2.id,
H1.startdate, H1.enddate, H2.startdate, H2.enddate
FROM HolidayItem AS H1
JOIN HolidayItem AS H2
ON (H1.startdate <= H2.enddate
AND H1.enddate >= H2.startdate)
AND H1.id < H2.id ;
To get the individual dates, just join to a calendar table on BETWEEN
startdate AND enddate.
Don't forget to add the important constraints. I don't quite understand
why your sample data has different start and end dates for the same
"holidayid" but however that may be, startdate ought to be part of a
composite unique key. Also, add the check constraint startdate <=
enddate
David Portas
SQL Server MVP
--
David Portas
SQL Server MVP
--|||The reason for the two start and end dates for the same holidayid is that it
is a table of holiday items and a holiday can have one or more items making
up the holiday. The reason for this is so that i do not record wends in
the holiday period.
Thanks very much for your help
john
"David Portas" wrote:

> SELECT H1.id, H2.id,
> H1.startdate, H1.enddate, H2.startdate, H2.enddate
> FROM HolidayItem AS H1
> JOIN HolidayItem AS H2
> ON (H1.startdate <= H2.enddate
> AND H1.enddate >= H2.startdate)
> AND H1.id < H2.id ;
> To get the individual dates, just join to a calendar table on BETWEEN
> startdate AND enddate.
> Don't forget to add the important constraints. I don't quite understand
> why your sample data has different start and end dates for the same
> "holidayid" but however that may be, startdate ought to be part of a
> composite unique key. Also, add the check constraint startdate <=
> enddate
> --
> David Portas
> SQL Server MVP
> --
>
> --
> David Portas
> SQL Server MVP
> --
>|||Hi Portas
does your query cover if start date starts after 2nd startdate and ends
before second end date.(intervening period_
similary of start date starts before 2nd startdate and ends after 2end end
dates(covering period)
and such scenarios
This union query may be used but not tested
SELECT dbo.HolidayItem.ID, dbo.HolidayItem.HolidayID,
dbo.HolidayItem.StartDate, dbo.HolidayItem.EndDate, HolidayItem_1.HolidayID
AS ClashID
FROM dbo.HolidayItem INNER JOIN
dbo.HolidayItem HolidayItem_1 ON
dbo.HolidayItem.StartDate >= HolidayItem_1.StartDate AND
dbo.HolidayItem.EndDate <= HolidayItem_1.EndDate AND
dbo.HolidayItem.HolidayID <> HolidayItem_1.HolidayID
union
SELECT dbo.HolidayItem.ID, dbo.HolidayItem.HolidayID,
dbo.HolidayItem.StartDate, dbo.HolidayItem.EndDate, HolidayItem_1.HolidayID
AS ClashID
FROM dbo.HolidayItem INNER JOIN
dbo.HolidayItem HolidayItem_1 ON
dbo.HolidayItem.HolidayID <> HolidayItem_1.HolidayID AND
dbo.HolidayItem.StartDate <= HolidayItem_1.StartDate
AND dbo.HolidayItem.StartDate >= HolidayItem_1.EndDate
union
SELECT dbo.HolidayItem.ID, dbo.HolidayItem.HolidayID,
dbo.HolidayItem.StartDate, dbo.HolidayItem.EndDate, HolidayItem_1.HolidayID
AS ClashID
FROM dbo.HolidayItem INNER JOIN
dbo.HolidayItem HolidayItem_1 ON
dbo.HolidayItem.HolidayID <> HolidayItem_1.HolidayID AND
dbo.HolidayItem.StartDate <= HolidayItem_1.StartDate
AND dbo.HolidayItem.StartDate <= HolidayItem_1.EndDate
union
SELECT dbo.HolidayItem.ID, dbo.HolidayItem.HolidayID,
dbo.HolidayItem.StartDate, dbo.HolidayItem.EndDate, HolidayItem_1.HolidayID
AS ClashID
FROM dbo.HolidayItem INNER JOIN
dbo.HolidayItem HolidayItem_1 ON
dbo.HolidayItem.HolidayID <> HolidayItem_1.HolidayID AND
dbo.HolidayItem.StartDate <= HolidayItem_1.StartDate
AND dbo.HolidayItem.StartDate >= HolidayItem_1.EndDate
union
SELECT dbo.HolidayItem.ID, dbo.HolidayItem.HolidayID,
dbo.HolidayItem.StartDate, dbo.HolidayItem.EndDate, HolidayItem_1.HolidayID
AS ClashID
FROM dbo.HolidayItem INNER JOIN
dbo.HolidayItem HolidayItem_1 ON
dbo.HolidayItem.HolidayID <> HolidayItem_1.HolidayID AND
dbo.HolidayItem.EndDate >= HolidayItem_1.StartDate AND
dbo.HolidayItem.EndDate <= HolidayItem_1.EndDate
r.d
"John" wrote:
> The reason for the two start and end dates for the same holidayid is that
it
> is a table of holiday items and a holiday can have one or more items makin
g
> up the holiday. The reason for this is so that i do not record wends in
> the holiday period.
> Thanks very much for your help
> john
> "David Portas" wrote:
>|||> does your query cover if start date starts after 2nd startdate and ends
> before second end date
Yes.
Compare your results to mine. There is a difference and I think some of
your joins need looking at. The following one looks wrong for a start
but your approach is basically sound, although a bit more typing than
mine!
dbo.HolidayItem.StartDate <= HolidayItem_1.StartDate
AND dbo.HolidayItem.StartDate <= HolidayItem_1.EndDate
David Portas
SQL Server MVP
--|||Your DDL had no key, you formatted the dates wrong, used IDENTITY and
lacked constraints. Is this what you really meant?
CREATE TABLE HolidaySchedules
(holiday_item INTEGER NOT NULL
start_date DATETIME NOT NULL
CHECK( << set to 00:00:00 Hrs>> ),
end_date DATETIME NOT NULL
CHECK( << set to 23:59:59.9999.. Hrs>> ),
CHECK (start_date < end_date),
PRIMARY KEY (holiday_item, start_date)); -- real key!!
INSERT INTO HolidaySchedules VALUES (1, '2005-08-05', '2005-08-10');
INSERT INTO HolidaySchedules VALUES (1, '2005-08-13', '2005-08-15');
INSERT INTO HolidaySchedules VALUES (2, '2005-08-01', '2005-08-05');
INSERT INTO HolidaySchedules VALUES (3, '2005-08-02', '2005-08-04');
INSERT INTO HolidaySchedules VALUES (4, '2005-08-13', '2005-08-20');
INSERT INTO HolidaySchedules VALUES (4, '2005-08-23', '2005-08-25');
s between different holidays. <<
Create a Calendar table with all the temporal data you use in your
enterprise. It will hlep with this query and a lot of others. First a
warm up query in a VIEW.
CREATE VIEW BadDates(cal_date, conflict_count)
AS
SELECT C.cal_date, COUNT(*)
FROM Calendar AS C1, HolidaySchedules AS H
WHERE C.cal_date BETWEEN H.start_date AND H.end_date
GROUP BY C.cal_date
HAVING COUNT(*) > 1;
This gives us rhe dates with conflicts. You can use those dates in the
desired query. Obviously, the VIEW can be made into a derived table or
CTE.
SELECT B.cal_date, H.holiday_item
FROM HolidaySchedules AS H, BadDates AS B
WHERE B.cal_date BETWEEN H.start_date AND H.end_date;
If you want to generate pairs of H.holiday_items, put this into another
VIEW and do a self-join on cal_dates. But I would do that in the front
end and not the database.|||yes, there are some joins where we need to add some more 'AND' OPERATOR.
FOR EX:
a date may start before second start date but ends before second end dates.
in this case we have to add one more condition : the first end date is
greater than second start date.
there is another scenario similar to this: it starts after first startdate
and ends after second end date.
bye
devaraj
"David Portas" wrote:

> SELECT H1.id, H2.id,
> H1.startdate, H1.enddate, H2.startdate, H2.enddate
> FROM HolidayItem AS H1
> JOIN HolidayItem AS H2
> ON (H1.startdate <= H2.enddate
> AND H1.enddate >= H2.startdate)
> AND H1.id < H2.id ;
> To get the individual dates, just join to a calendar table on BETWEEN
> startdate AND enddate.
> Don't forget to add the important constraints. I don't quite understand
> why your sample data has different start and end dates for the same
> "holidayid" but however that may be, startdate ought to be part of a
> composite unique key. Also, add the check constraint startdate <=
> enddate
> --
> David Portas
> SQL Server MVP
> --
>
> --
> David Portas
> SQL Server MVP
> --
>sql

Monday, March 26, 2012

finding bad date

I have a database where a varchar field is being used to store dates. I wrot
e
the following function to check if the data is a valid date. If it is not a
valid date, Null is returned.
ALTER function f_ToDate(@.inDate varchar(50))
returns datetime
begin
declare @.returndate datetime
if isdate(@.inDate) = 0
select @.returndate = null
else
select @.returndate = convert(datetime,@.inDate,101)
return @.returndate
end
In my database, I have a table called Generation with a field called
CreateDate. When I run the following query, I get an error message stating
that “syntax error converting datetime from character string”
select dbo.f_ToDate(Generation.CreationDate) from Generation
To check, I ran the following query and it returned all null records which
is expected
select CreationDate from general where isdate(CreationDate) = 0
The following returns no records which is expected.
select CreationDate from general where isdate(CreationDate) = 0 and
CreationDate is not Null.
I can’t find the record that is causing “select
dbo.f_ToDate(Generation.CreationDate) from Generation” to fail.I have had a similar issue w/ Dates. A quick and dirty way that I used was t
o
export out the records using DTS to a table that mirrored the working one.
Only change I made was to change the varchar date field to a true datetime
field in the temp table. In my dts package I set the max number of errors to
the max (999) and started the export.
In my case I had 632 fewer records in my temp table after the export. I ran
a NOT EXISTS against the tables and was able to find the 632 records w/ bad
dates in my production table.
If the number of records w/ bad dates is GT 999, you will have to do the
export in bacthes to find all the bad recs.
Just a thought!
"Emma" wrote:

> I have a database where a varchar field is being used to store dates. I wr
ote
> the following function to check if the data is a valid date. If it is not
a
> valid date, Null is returned.
> ALTER function f_ToDate(@.inDate varchar(50))
> returns datetime
> begin
> declare @.returndate datetime
> if isdate(@.inDate) = 0
> select @.returndate = null
> else
> select @.returndate = convert(datetime,@.inDate,101)
> return @.returndate
> end
>
> In my database, I have a table called Generation with a field called
> CreateDate. When I run the following query, I get an error message stating
> that “syntax error converting datetime from character string”
> select dbo.f_ToDate(Generation.CreationDate) from Generation
> To check, I ran the following query and it returned all null records which
> is expected
> select CreationDate from general where isdate(CreationDate) = 0
> The following returns no records which is expected.
> select CreationDate from general where isdate(CreationDate) = 0 and
> CreationDate is not Null.
> I can’t find the record that is causing “select
> dbo.f_ToDate(Generation.CreationDate) from Generation” to fail.
>|||Emma,
The convert function with style 101 is supposed to be used when converting
from datetime to char or varchar. Can you execute:
select case when isdate(CreationDate) = 0 then null else convert(datetime,
CreationDate)
from Generation
AMB
"Emma" wrote:

> I have a database where a varchar field is being used to store dates. I wr
ote
> the following function to check if the data is a valid date. If it is not
a
> valid date, Null is returned.
> ALTER function f_ToDate(@.inDate varchar(50))
> returns datetime
> begin
> declare @.returndate datetime
> if isdate(@.inDate) = 0
> select @.returndate = null
> else
> select @.returndate = convert(datetime,@.inDate,101)
> return @.returndate
> end
>
> In my database, I have a table called Generation with a field called
> CreateDate. When I run the following query, I get an error message stating
> that “syntax error converting datetime from character string”
> select dbo.f_ToDate(Generation.CreationDate) from Generation
> To check, I ran the following query and it returned all null records which
> is expected
> select CreationDate from general where isdate(CreationDate) = 0
> The following returns no records which is expected.
> select CreationDate from general where isdate(CreationDate) = 0 and
> CreationDate is not Null.
> I can’t find the record that is causing “select
> dbo.f_ToDate(Generation.CreationDate) from Generation” to fail.
>|||Thanks Jay for your response. I did just what you said. The number of record
s
exported to the temp table was the same as in my original table, and the
query work on the temp table and not on the original. I can’t figure it ou
t.
"Jay Kusch" wrote:
> I have had a similar issue w/ Dates. A quick and dirty way that I used was
to
> export out the records using DTS to a table that mirrored the working one.
> Only change I made was to change the varchar date field to a true datetime
> field in the temp table. In my dts package I set the max number of errors
to
> the max (999) and started the export.
> In my case I had 632 fewer records in my temp table after the export. I ra
n
> a NOT EXISTS against the tables and was able to find the 632 records w/ ba
d
> dates in my production table.
> If the number of records w/ bad dates is GT 999, you will have to do the
> export in bacthes to find all the bad recs.
> Just a thought!
> "Emma" wrote:
>|||Thanks. That worked.
"Alejandro Mesa" wrote:
> Emma,
> The convert function with style 101 is supposed to be used when converting
> from datetime to char or varchar. Can you execute:
> select case when isdate(CreationDate) = 0 then null else convert(datetime,
> CreationDate)
> from Generation
>
> AMB
> "Emma" wrote:
>

Finding a users is adult or minor using a simple select query

my problem is that i need to find if a user is adult or minor using a
simple select query .I have the date of birth of the user and a column
named isadult as well in the table but the isadult column also updates
only when the user enters or updates his/her details.
I even tried using a sql function bt it wont allow me to use getdate
function.

Any solution are welcome unless it makes me fetch records using a
select query in a stored procedure.

Thanx in AdvanceUdit Handa wrote:
> my problem is that i need to find if a user is adult or minor using a
> simple select query .I have the date of birth of the user and a
column
> named isadult as well in the table but the isadult column also
updates
> only when the user enters or updates his/her details.
> I even tried using a sql function bt it wont allow me to use getdate
> function.

Can you post the exact syntax for the SQL function you used?|||On 23 Mar 2005 03:58:56 -0800, Udit Handa wrote:

>my problem is that i need to find if a user is adult or minor using a
>simple select query .I have the date of birth of the user and a column
>named isadult as well in the table but the isadult column also updates
>only when the user enters or updates his/her details.
>I even tried using a sql function bt it wont allow me to use getdate
>function.
>Any solution are welcome unless it makes me fetch records using a
>select query in a stored procedure.
>Thanx in Advance

Hi Udit,

The best solution is to remove the IsAdult column, drop the function and
create a view instead:

CREATE VIEW MyView
AS
SELECT Col1, Col2, ..., ColN, BirthDate,
CASE WHEN BirthDate > DATEADD (year, -18, CURRENT_TIMESTAMP)
THEN 'Underage'
ELSE 'Adult'
END AS IsAdult
(untested)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||>> I need to find if a user is adult or minor using a simple select
query .I have the date of birth of the user and a column named isadult
as well in the table but the isadult column also updates only when the
user enters or updates his/her details. <<

Now you have learned one of the many reasons that we do not use flags
in SQL, like we did in punch card systems. Drop the "isadult" flag; it
is a redundant computed column and create a VIEW that uses the date of
birth with the CURRENT-TIMESTAMP to determine this fact.

I also hope that you are not using the proprietary, low-level BIT data
type for this incorrect design.

Finding a user that has multiple log-ins at the same time

I have a table that contains the following

UserName - Which is unique to each user

TimeStart - Which is the time and date that the user logs in

TimeEnd - Which is the time and date that the user logs out

Using SQL, how do you find who has logged in using the same account within the same time period. In other words, Two people are using the same username and are logged in at the same time.

Try this query....


Select
MainQ.*
From
UserLog MainQ
Join
(
Select

Main.UserName,
Main.TimeStart,
Main.TimeEnd
From
UserLog Main
Join UserLog Started On Main.UserName = Started.UserName
And Main.TimeStart <= Started.TimeStart
And Main.TimeEnd >= Started.TimeStart

Group BY
Main.UserName,
Main.TimeStart,
Main.TimeEnd
Having Count(*) <> 1
) as Data
On MainQ.UserName = Data.UserName
And MainQ.TimeStart >= Data.TimeStart
And MainQ.TimeStart <= Data.TimeEnd

Friday, March 23, 2012

Finding a Member

Hi,
I try to evaluate a functionality to find a date-Member. Wath we need
is, we search the first existing Date in our Time-Dimension, which is,
say 11 days before the actual-date. Since such a Member maybe not
exits, the function should return the smallest existing Date bigger then the
one we are searching for.

MEMBER [MEASURES].[date1] AS
DATEADD("d", -11, CDate([Zeit].[Zeit].CURRENTMEMBER.MEMBER_CAPTION))
MEMBER [MEASURES].[mydate] AS
FILTER([Zeit].[Zeit].[Datum].members,
cdate([Zeit].[Zeit].[Datum].value) >= [MEASURES].[date1]).Item(0)
It doesn’t work in that way.
Can anybody give me some Help.
Thank you very much.

Bahram.

Looks like the problem here with the use of .Value function, which will retrieve cell value. If you are using AS2005, you can rewrite the Filter to be

FILTER([Zeit].[Zeit].[Datum].members, [Zeit].[Zeit].CurrentMember.MemberValue >= [MEASURES].[date1]).Item(0))

HTH

Mosha (http://www.mosha.com/msolap)

|||

Hi,

I tried your Formula. It doesn't work, i.e. it returns all Dates (([Zeit].[Zeit].[Datum].members). I think, it's becouse of the calculation of [MEASURES].[date1]. It uses the Currentmember and wenn the filter itterates through the members, it calculates the [MEASURES].[date1] again and again.

I don't know, if its correct or not!

Thanke you

|||Sorry - I didn't notice that date1 was going against CurrentMember in Zeit dimension. It needs to be fixed on the particular date that you are interested in for this Filter to work correctly.sql

Find values from record that had a max value in a group by

I am looking for the MS SQL variant of the oracle 'KEEP DENSE_RANK' construction.

If you have a table like this:

key date item 1 20070101 Apple 1 20070202 Banana 1 20070303 Cherry

The query for retrieving the item from the last date should pick the Cherry, but what would be the most efficient way to do this (without using multiple queries, in oracle I don't need a sub query!).

You would like to do something like:

Select Key, max(Date) as LastDate, PickLastValue(Cherry) on Date desc

from Table

group by Key.

any suggestions?

hans

You can do the same funciton in SQL Server 2005..

Code Snippet

Create Table #data (

[key] Varchar(100) ,

[date] Varchar(100) ,

[item] Varchar(100)

);

Insert Into #data Values('1','20070101','Apple');

Insert Into #data Values('1','20070202','Banana');

Insert Into #data Values('1','20070303','Cherry');

Insert Into #data Values('2','20070101','Apple');

Insert Into #data Values('2','20070202','Banana');

Code Snippet

--Over all

;With CTE

as

(

Select [key],[date],[item],DENSE_RANK() Over (Order By [date] Desc) rank From #Data

)

Select [key],[date],[item] from CTE Where rank=1

Code Snippet

--For each Key

;With CTE

as

(

Select [key],[date],[item],DENSE_RANK() Over (Partition By [Key] Order By [date] Desc) rank From #Data

)

Select [key],[date],[item],rank from CTE Where rank=1

|||

If you use sql server 2000 then you have to use the subquery...

Code Snippet

--For Overall

Select * from #data Where [date] in (Select max(date) From #data)

--For Each Key

Select * from #data Data

Join (Select [Key], max(date) date From #data Group By [Key]) Sub On

Sub.[Key]=Data.[Key] and Sub.date=Data.date

|||

This will do!

thanx

hans

Wednesday, March 21, 2012

find value based on max(date)

I know I have done this before, but cannot for the life of me remember how.

I am trying to determine return the current (last added) deduction amount for each deduction type for each employee

Sample Table:
employee|Deduction_type|Date_entered|Amount
1|MED|1/1/2007|50
1|DEPC|1/1/2007|100
1|MED|1/8/2007|50
1|DEPC|1/8/2007|100
1|MED|1/15/2007|150
2|MED|1/1/2007|35
2|DEPC|1/1/2007|100
2|MED|1/8/2007|35
2|DEPC|1/8/2007|75
2|MED|1/15/2007|35

Any suggestions?select t.employee
, t.Deduction_type
, t.Date_entered
, t.Amount
from Sample as t
inner
join (
select employee
, Deduction_type
, max(Date_entered) as max_date
from Sample
group
by employee
, Deduction_type
) as m
on m.employee = t.employee
and m.Deduction_type = t.Deduction_type
and m.max_date = t.Date_enteredsql

Find UNICODE Data

How can you find UNICODE date within char & varchar fields in table.
I am in the midst of a migration and need to evaluate all the fields that
may have €
chinese, french and thus require more char space in the new structure.
This is a matter of great urgency so any help greatly appreciated.
Thanks
marcIf the fields are not a Unicode data type, then there is no Unicode data in
them. If the characters are not supported by the code page of the field
(defined by its by collation), they are lost (will show up as '?'). If they
are supported by the code page, you can search for them like you normally
would, or by using full-text search.
David Barber [MS]
SQL Server Documentation Team
This posting is provided "AS IS" with no warranties, and confers no rights
"marcmc" <marcmc@.discussions.microsoft.com> wrote in message
news:699A4648-85DC-4B5F-A876-6B223CD4A5DE@.microsoft.com...
> How can you find UNICODE date within char & varchar fields in table.
> I am in the midst of a migration and need to evaluate all the fields that
> may have ?
> chinese, french and thus require more char space in the new structure.
> This is a matter of great urgency so any help greatly appreciated.
> Thanks
> marc

Find the newest date of 2 date fields

I've 2 date fields clidlp,clidlc in my data base table. How do I find the newest dates between the fields? Thanks for your help!

Hello, you can use a CASE statement in your SQL Query

Eample:
SELECT CASE WHEN clidlp > clidlc THEN clidlp ELSE clidlc END AS NewestDate
FROM [Table]

Find the nearest date of one column of a table from another table

I have two tables Expense_Addl and ExchangeRates
These are the scripts
CREATE TABLE Expense_Addl (
FileId int,
HostAmt money,
HostCurrencyCd char(4),
LockDt smalldatetime
)
INSERT INTO Expense_addl values (1001, 500, 'USD', '2006-06-15')
INSERT INTO Expense_addl values (1001, 500, 'USD', '2006-06-19')
INSERT INTO Expense_addl values (1001, 500, 'USD', '2002-01-01')
In the above table HostCurrencycd can be any currenycode like 'USD',
'INR', YEN'
CREATE TABLE ExchangeRates
(CurrencyCd CHAR(4), ExchangeRate MONEY, ExchangeRateDate
SMALLDATETIME)
INSERT INTO ExchangeRates values ('USD', 0.45, '2006-06-21')
INSERT INTO ExchangeRates values ('USD', 0.40, '2006-06-14')
Now i have to update the HostAmt in Expense_Addl table taking
exchangerate for the hostcurrencycd from table ExchangeRates
for the nearest date like this
For e.g. HOstAmt in first row should take exchangerate as 0.40 because
lockdt 15th june is closet to 14th june
Similarly HOstAmt in second row should take exchangerate as 0.45
because lockdt 19th june is closet to 21st june
Similarly HOstAmt in third row should take exchangerate as 0.40 because
lockdt 01st jan is closet to 14th june
I am trying like below but not getting the correct results.
UPDATE EA
SET HostAmt = ROUND(CONVERT(MONEY,(ISNULL(((CONVERT(FL
OAT, EA.HostAmt))
* 100) / NULLIF(ISNULL(ER1.ExchangeRate,0),0),0))), 4)
FROM Expense_Addl EA(NOLOCK)
INNER JOIN ExchangeRates ER1(NOLOCK) ON EA.HostCurrencyCd =
ER1.CurrencyCd
INNER JOIN
(SELECT CurrencyCd, MAX(ExchangeRateDate) As ExchangeRateDate
FROM ExchangeRates ER ,Expense_Addl EA(NOLOCK) Where
ER.ExchangeRateDate <= EA.lockdt
GROUP BY ER.CurrencyCd
) T1
ON T1.ExchangeRateDate = ER1.ExchangeRateDate AND T1.CurrencyCd =
ER1.CurrencyCd
Can anyone help me with this ?
Regards,
Rajeev RajputHi Rajeev,
I don't know what you do that convert and nullif and all.
But I have substituted a query that will give you the exchange rate.
this update works. But no where clause for your Expense_addl.
I didn't try to figure out from your query :)
UPDATE Expense_Addl
SET HostAmt = ROUND(CONVERT(MONEY,(ISNULL(((CONVERT(FL
OAT,
Expense_Addl.HostAmt))
* 100) / NULLIF(ISNULL((select top 1 ExchangeRate from ExchangeRates ER1
where
ER1.CurrencyCd = Expense_Addl.HostCurrencyCD
order by abs(datediff(dd,ER1.ExchangeRateDate,LockDt)) asc),0),0),0))), 4)
Hope this helps.
--
-Omnibuzz (The SQL GC)
http://omnibuzz-sql.blogspot.com/|||Hi,
It is working but i have one issue with it.
When Lockdt is NULL i am getting this part as 1 -->>>>>
select top 1 ExchangeRate from ExchangeRates ER1
where
ER1.CurrencyCd = Expense_Addl.HostCurrencyCD
order by abs(datediff(dd,ER1.ExchangeRateDate,LockDt)) asc
rather i should get it as NULL
Could you please help ?
Omnibuzz thanks in advance :)
Omnibuzz wrote:

> Hi Rajeev,
> I don't know what you do that convert and nullif and all.
> But I have substituted a query that will give you the exchange rate.
> this update works. But no where clause for your Expense_addl.
> I didn't try to figure out from your query :)
> UPDATE Expense_Addl
> SET HostAmt = ROUND(CONVERT(MONEY,(ISNULL(((CONVERT(FL
OAT,
> Expense_Addl.HostAmt))
> * 100) / NULLIF(ISNULL((select top 1 ExchangeRate from ExchangeRates ER1
> where
> ER1.CurrencyCd = Expense_Addl.HostCurrencyCD
> order by abs(datediff(dd,ER1.ExchangeRateDate,LockDt)) asc),0),0),0))),
4)
>
> Hope this helps.
> --
> -Omnibuzz (The SQL GC)
> http://omnibuzz-sql.blogspot.com/

Find the most recent date of the past

Hello,

I've a table which contains the nest following data:

Date Sales Price

01-01-07 5,00

31-03-07 6,00

16-04-07 5.75

26-04-07 6.25

For example, today is 18-04-07. In my report I want to show the most recent Sales Price, but not the price of next week. I want to see the SalesPrice of 5.75.

How can I get it?

Thx!

This may work... there's probably an easier way.

select top 1 [date], [salesprice]

from table

group by [date], [salesprice]

having max(convert(varchar(10),[date],112)) < convert(varchar(10),current_timestamp,112)

order by [date] desc

cheers,

Andrew

|||

Here's a version without the grouping. Try this:

select top 1 SalesPrice

from PriceInfoTable

where Date < getdate()

order by Date desc

Jarret

|||

Jarret,

Your solutions works, but I discovered that my problem is a little bit more complex. I still have the same table, but in the table I have more items. My table looks like (for example):

No. Date Sales Price

001 01-01-07 5,00

001 31-03-07 6,00

001 16-04-07 5.75

001 26-04-07 6.25

002 21-01-07 7,00

002 27-02-07 7,00

002 06-04-07 7.75

002 26-04-07 7.25

003 11-01-07 2,00

003 17-02-07 1,00

003 01-04-07 0.75

003 26-04-07 1.25

If I use your code, I only get ItemNo. 001 with a price of 5.75. But I want for every item the most recent price:

001 5.75

002 7.75

003 0.75

I've tried some options, but I can't get the solution. Do you have any suggestions?

|||

Here's two ways you could do it...

select distinct t1.id,

( select top 1 price

from PriceInfoTable

where Date < getdate()

and t1.id = #t.id

order by Date desc

) price

from PriceInfoTable t1

select t1.id, t1.price

from PriceInfoTable t1

inner join (

select id, max(date) as MaxDate

from PriceInfoTable

where Date < getdate()

group by id

) t2 on t1.id = t2.id and t1.date = t2.MaxDate

order by t1.id

Hope this helps.

Jarret

|||

Jarret,

I don't get the first option.

Can you tell me what the function of 't1.id' is? And also from 't1.id=#t.id.'? Maybe them I can implement it to my query......

thx

|||

No the first option has a type, it is actually:

select distinct t1.id,

( select top 1 price

from PriceInfoTable t2

where Date < getdate()

and t1.id = t2.id

order by Date desc

) price

from PriceInfoTable t1

You can also use this query which is the 3rd option:

SELECT [No], SalesPrice

FROM PriceInfoTable p1

WHERE Date = (SELECT MAX(Date) FROM PriceInfoTable p2 WHERE p2.No = p1.No AND Date < GETDATE())

Shyam

|||

Sorry,

I was working with my own sample query to get the results you needed and was using a temp table (#t) to hold the data.

The t1.id corresponds to your "No." field and the #t corresponds to the PriceInfoTable in the subquery. Shyam's post has my query with it fixed. Sorry for the inconvenience.

Jarret

|||

Jarret/Shyam,

I got all the 3 solutions implemented and they are working Smile

But the next step for me is to add another column at the "select top"-selection.

In my table I have also a 'Sales Code'. In my report the user must set a filter on this 'Sales Code' (with a parameter). The table looks like:

No. StartingDate Sales Price Sales Code

001 01-01-07 5,00 SC01

001 31-03-07 6,00 SC01

001 16-04-07 5.75 SC02

001 26-04-07 6.25 SC01

If the user select SC01, the price of 6.00 has to be displayed. By selecting SC02, 5.75.

I have tried to insert 'Sales Code' in one of your suggestions on this way,

select distinct t1.id,

( select top 1 price, Sales Code

from PriceInfoTable

where Date < getdate()

and t1.id = #t.id

order by Date desc

) price

from PriceInfoTable t1

but an error returns.

Also inserting 'Sales Code' after the 'Select distinct t1.id'-part, wasn't the right way. By doing this the same price was given to every sales code.

Can you help me out?

Thx a lot!

|||

Try this:

select t1.id, t1.price, t1.[sales code]

from PriceInfoTable t1

inner join (

select id, max(date) as MaxDate

from PriceInfoTable

where Date < getdate()

and [Sales Code] = @.SalesCodeParameter

group by id

) t2 on t1.id = t2.id and t1.date = t2.MaxDate

order by t1.id

Hope this helps.

Jarret

|||

Jarret,

thx for your help. Your suggestion is working! Smile

But I see that I've me an error by posting an example of the table. The field StartingDate is not only the date but also the time, it's the starting date and time. So the code-part of

WHERE([Starting Date Time]) < GETDATE

has to be something else. I have tried GETDATETIME, but that was not correct. How can I solve it?

Starting Date Time is a combined field. The fields Starting Date and Starting Time are also seperated available, if necessary.

Thx

|||

Try this:

WHERE([Starting Date Time]) < GETDATE()

Jarret

|||

Jarret,

I did that suggestion and it didn't worked out.

The problem is that the report is filtering only on date, not on date and time....

Do you have a suggestion?

Thx

|||

This will remove the time from the current date time.

WHERE([Starting Date Time]) < convert(varchar, GETDATE(), 101)

If you need to remove the time part off of [Starting Date Time], just wrap it in the convert statement as well.

Hope this helps.

Jarret

|||

Jarret,

More than one price for a date can be inserted In my table. I can insert a price and give it a starting time of 22.00 tonight. Of course I want to see the price of now if it is not yet 22.00.

I think I need more something like GETTIME or someting like that.

I was thinking of a statement with

WHERE(([Starting Date Time]) < GETDATE() and Starting Date Time]) < GETTIME()

in it.

But this one is not working.

Do you have any suggestion?

Thx

Find the most recent date of the past

Hello,

I've a table which contains the nest following data:

Date Sales Price

01-01-07 5,00

31-03-07 6,00

16-04-07 5.75

26-04-07 6.25

For example, today is 18-04-07. In my report I want to show the most recent Sales Price, but not the price of next week. I want to see the SalesPrice of 5.75.

How can I get it?

Thx!

This may work... there's probably an easier way.

select top 1 [date], [salesprice]

from table

group by [date], [salesprice]

having max(convert(varchar(10),[date],112)) < convert(varchar(10),current_timestamp,112)

order by [date] desc

cheers,

Andrew

|||

Here's a version without the grouping. Try this:

select top 1 SalesPrice

from PriceInfoTable

where Date < getdate()

order by Date desc

Jarret

|||

Jarret,

Your solutions works, but I discovered that my problem is a little bit more complex. I still have the same table, but in the table I have more items. My table looks like (for example):

No. Date Sales Price

001 01-01-07 5,00

001 31-03-07 6,00

001 16-04-07 5.75

001 26-04-07 6.25

002 21-01-07 7,00

002 27-02-07 7,00

002 06-04-07 7.75

002 26-04-07 7.25

003 11-01-07 2,00

003 17-02-07 1,00

003 01-04-07 0.75

003 26-04-07 1.25

If I use your code, I only get ItemNo. 001 with a price of 5.75. But I want for every item the most recent price:

001 5.75

002 7.75

003 0.75

I've tried some options, but I can't get the solution. Do you have any suggestions?

|||

Here's two ways you could do it...

select distinct t1.id,

( select top 1 price

from PriceInfoTable

where Date < getdate()

and t1.id = #t.id

order by Date desc

) price

from PriceInfoTable t1

select t1.id, t1.price

from PriceInfoTable t1

inner join (

select id, max(date) as MaxDate

from PriceInfoTable

where Date < getdate()

group by id

) t2 on t1.id = t2.id and t1.date = t2.MaxDate

order by t1.id

Hope this helps.

Jarret

|||

Jarret,

I don't get the first option.

Can you tell me what the function of 't1.id' is? And also from 't1.id=#t.id.'? Maybe them I can implement it to my query......

thx

|||

No the first option has a type, it is actually:

select distinct t1.id,

( select top 1 price

from PriceInfoTable t2

where Date < getdate()

and t1.id = t2.id

order by Date desc

) price

from PriceInfoTable t1

You can also use this query which is the 3rd option:

SELECT [No], SalesPrice

FROM PriceInfoTable p1

WHERE Date = (SELECT MAX(Date) FROM PriceInfoTable p2 WHERE p2.No = p1.No AND Date < GETDATE())

Shyam

|||

Sorry,

I was working with my own sample query to get the results you needed and was using a temp table (#t) to hold the data.

The t1.id corresponds to your "No." field and the #t corresponds to the PriceInfoTable in the subquery. Shyam's post has my query with it fixed. Sorry for the inconvenience.

Jarret

|||

Jarret/Shyam,

I got all the 3 solutions implemented and they are working Smile

But the next step for me is to add another column at the "select top"-selection.

In my table I have also a 'Sales Code'. In my report the user must set a filter on this 'Sales Code' (with a parameter). The table looks like:

No. StartingDate Sales Price Sales Code

001 01-01-07 5,00 SC01

001 31-03-07 6,00 SC01

001 16-04-07 5.75 SC02

001 26-04-07 6.25 SC01

If the user select SC01, the price of 6.00 has to be displayed. By selecting SC02, 5.75.

I have tried to insert 'Sales Code' in one of your suggestions on this way,

select distinct t1.id,

( select top 1 price, Sales Code

from PriceInfoTable

where Date < getdate()

and t1.id = #t.id

order by Date desc

) price

from PriceInfoTable t1

but an error returns.

Also inserting 'Sales Code' after the 'Select distinct t1.id'-part, wasn't the right way. By doing this the same price was given to every sales code.

Can you help me out?

Thx a lot!

|||

Try this:

select t1.id, t1.price, t1.[sales code]

from PriceInfoTable t1

inner join (

select id, max(date) as MaxDate

from PriceInfoTable

where Date < getdate()

and [Sales Code] = @.SalesCodeParameter

group by id

) t2 on t1.id = t2.id and t1.date = t2.MaxDate

order by t1.id

Hope this helps.

Jarret

|||

Jarret,

thx for your help. Your suggestion is working! Smile

But I see that I've me an error by posting an example of the table. The field StartingDate is not only the date but also the time, it's the starting date and time. So the code-part of

WHERE([Starting Date Time]) < GETDATE

has to be something else. I have tried GETDATETIME, but that was not correct. How can I solve it?

Starting Date Time is a combined field. The fields Starting Date and Starting Time are also seperated available, if necessary.

Thx

|||

Try this:

WHERE([Starting Date Time]) < GETDATE()

Jarret

|||

Jarret,

I did that suggestion and it didn't worked out.

The problem is that the report is filtering only on date, not on date and time....

Do you have a suggestion?

Thx

|||

This will remove the time from the current date time.

WHERE([Starting Date Time]) < convert(varchar, GETDATE(), 101)

If you need to remove the time part off of [Starting Date Time], just wrap it in the convert statement as well.

Hope this helps.

Jarret

|||

Jarret,

More than one price for a date can be inserted In my table. I can insert a price and give it a starting time of 22.00 tonight. Of course I want to see the price of now if it is not yet 22.00.

I think I need more something like GETTIME or someting like that.

I was thinking of a statement with

WHERE(([Starting Date Time]) < GETDATE() and Starting Date Time]) < GETTIME()

in it.

But this one is not working.

Do you have any suggestion?

Thx

find the lastest date among many fields

I have seven date fields, and I need to select the lastest date among the
seven fields.
Example
table1
ID, date1, date2, date3, date4,date5, date6, date7
Result should show '10/07/2005'
Thanks,
Culam
CREATE TABLE table1
(
id int,
date1 smalldatetime,
date2 smalldatetime,
date3 smalldatetime,
date4 smalldatetime,
date5 smalldatetime,
date6 smalldatetime,
date7 smalldatetime
)
INSERT INTO table1
(id, date1, date2, date3, date4, date5, date6, date7)
VALUES (1, '10/01/2005', '10/02/2005', '10/07/2005', '10/03/2005',
'10/04/2005', '10/06/2005', '10/05/2005')7 date columns in a row looks suspiciously like poor normalization.
Anyway, try the following. Nulls will be ignored.
SELECT id,
(SELECT MAX(dt)
FROM
(SELECT date1 AS dt UNION ALL
SELECT date2 UNION ALL
SELECT date3 UNION ALL
SELECT date4 UNION ALL
SELECT date5 UNION ALL
SELECT date6 UNION ALL
SELECT date7) AS X)
AS maxdate
FROM Table1
David Portas
SQL Server MVP
--|||Culam,
I'm not a design expert but I think you may need to work on normalizing this
a bit.
You could try something like:
SELECT ID,
(SELECT MAX(DATEVALUE)
FROM
(SELECT DATE1 AS DATEVALUE FROM TABLE1 UNION ALL
SELECT DATE2 FROM TABLE1 UNION ALL
SELECT DATE3 FROM TABLE1 UNION ALL
SELECT DATE4 FROM TABLE1 UNION ALL
SELECT DATE5 FROM TABLE1 UNION ALL
SELECT DATE6 FROM TABLE1 UNION ALL
SELECT DATE7 FROM TABLE1)
AS Z)
FROM TABLE1
or use the MAX function with a temp table.
HTH
Jerry
"culam" <culam@.discussions.microsoft.com> wrote in message
news:49405690-F7F1-4E6A-BCCD-27407C0E35E7@.microsoft.com...
>I have seven date fields, and I need to select the lastest date among the
> seven fields.
> Example
> table1
> ID, date1, date2, date3, date4,date5, date6, date7
> Result should show '10/07/2005'
> Thanks,
> Culam
> CREATE TABLE table1
> (
> id int,
> date1 smalldatetime,
> date2 smalldatetime,
> date3 smalldatetime,
> date4 smalldatetime,
> date5 smalldatetime,
> date6 smalldatetime,
> date7 smalldatetime
> )
> INSERT INTO table1
> (id, date1, date2, date3, date4, date5, date6, date7)
> VALUES (1, '10/01/2005', '10/02/2005', '10/07/2005', '10/03/2005',
> '10/04/2005', '10/06/2005', '10/05/2005')|||Try,
CREATE TABLE t1
(
id int,
date1 smalldatetime,
date2 smalldatetime,
date3 smalldatetime,
date4 smalldatetime,
date5 smalldatetime,
date6 smalldatetime,
date7 smalldatetime
)
INSERT INTO t1
(id, date1, date2, date3, date4, date5, date6, date7)
VALUES (1, '10/01/2005', '10/02/2005', '10/07/2005', '10/03/2005',
'10/04/2005', '10/06/2005', '10/05/2005')
select [id], max(c1)
from
(
select [id], date1
from t1
union all
select [id], date2
from t1
union all
select [id], date3
from t1
union all
select [id], date4
from t1
union all
select [id], date5
from t1
union all
select [id], date6
from t1
union all
select [id], date7
from t1
) as t2([id], c1)
group by [id]
-- or
select
[id],
max(
case t2.c1
when 1 then date1
when 2 then date2
when 3 then date3
when 4 then date4
when 5 then date5
when 6 then date6
when 7 then date7
end
)
from t1 cross join (select 1 as c1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 union all select 7)
as t2
group by [id]
drop table t1
go
AMB
"culam" wrote:

> I have seven date fields, and I need to select the lastest date among the
> seven fields.
> Example
> table1
> ID, date1, date2, date3, date4,date5, date6, date7
> Result should show '10/07/2005'
> Thanks,
> Culam
> CREATE TABLE table1
> (
> id int,
> date1 smalldatetime,
> date2 smalldatetime,
> date3 smalldatetime,
> date4 smalldatetime,
> date5 smalldatetime,
> date6 smalldatetime,
> date7 smalldatetime
> )
> INSERT INTO table1
> (id, date1, date2, date3, date4, date5, date6, date7)
> VALUES (1, '10/01/2005', '10/02/2005', '10/07/2005', '10/03/2005',
> '10/04/2005', '10/06/2005', '10/05/2005')|||Jerry Spivey wrote:
> SELECT ID,
> (SELECT MAX(DATEVALUE)
> FROM
> (SELECT DATE1 AS DATEVALUE FROM TABLE1 UNION ALL
> SELECT DATE2 FROM TABLE1 UNION ALL
> SELECT DATE3 FROM TABLE1 UNION ALL
> SELECT DATE4 FROM TABLE1 UNION ALL
> SELECT DATE5 FROM TABLE1 UNION ALL
> SELECT DATE6 FROM TABLE1 UNION ALL
> SELECT DATE7 FROM TABLE1)
> AS Z)
> FROM TABLE1
>
Did you try that with more than one row of dates? If Culam wants just a
single maximum date then you may as well remove the outer part of the
query.
David Portas
SQL Server MVP
--|||Was just about to post how your code rocks and mine is would be sluggish
with all of the table scans! ;-) Dropped all of the extra FROM TABLE1.
Thanks for the follow up...always learning from you.
Jerry
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1129057820.822069.139720@.o13g2000cwo.googlegroups.com...
> Jerry Spivey wrote:
> Did you try that with more than one row of dates? If Culam wants just a
> single maximum date then you may as well remove the outer part of the
> query.
> --
> David Portas
> SQL Server MVP
> --
>|||David,
Might want to change it up a bit for multiple rows to something like this:
SELECT TOP 1 X.ID, MAX(X.MAXDATE) AS 'MAX DATE'
FROM
(SELECT id,
(SELECT MAX(dt)
FROM
(SELECT date1 AS dt UNION ALL
SELECT date2 UNION ALL
SELECT date3 UNION ALL
SELECT date4 UNION ALL
SELECT date5 UNION ALL
SELECT date6 UNION ALL
SELECT date7) AS X)
AS maxdate
FROM Table1) AS X
GROUP BY X.ID
ORDER BY MAX(X.MAXDATE)DESC
Thoughts?
Thanks
Jerry
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:%23xMgPgpzFHA.2792@.tk2msftngp13.phx.gbl...
> Was just about to post how your code rocks and mine is would be sluggish
> with all of the table scans! ;-) Dropped all of the extra FROM TABLE1.
> Thanks for the follow up...always learning from you.
> Jerry
> "David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
> news:1129057820.822069.139720@.o13g2000cwo.googlegroups.com...
>|||Just my usualy caveats around TOP: Use an ORDER BY that's guaranteed to
be unique or specify TOP WITH TIES. Random results due to ties can be a
lot of hassle.
David Portas
SQL Server MVP
--