Showing posts with label table. Show all posts
Showing posts with label table. Show all posts

Friday, March 30, 2012

how to get top three salary getters from table employee

Dear All,
i want to know how to get top three salary getters from the employee(eid , ename, salary) table

i tried this
select top 3 salary from employee order by salary desc

but it gives me top three salary record say there is salary 1000,1200,1300,1300,1500
then my query return me 1500,1300,1200 whereas i want to 1500,1300,1300,1200

how can i do it

please help

thanks


You can run this query:

SELECT * FROM YourTable
WHERE Salary IN (
SELECT DISTINCT TOP 3 Salary FROM YourTable
ORDER BY Salary DESC )
ORDER BY Salary DESCsql

How to get Top 1 in Join on Calendar table...?

I would only like to see the latest calendar Sale per #c1 record as (select
top
1 * from calen order by ondate desc)
It doesn't matter if it's type is RA or DS, just the latest ONE.
set nocount on
-- Hist
select id = 2 ,userid = 'CANDUML1' ,Ref = 'Needs' ,ondate = '03/06/2006' ,Ac
tv =
'DS' ,Num = 500 ,Type = 'A' ,recid = '123457'
into #h
insert #h
select id = 1 ,userid = 'ARMEC1' ,Ref = 'Needs' ,ondate = '01/26/2006' ,Actv
=
'RA' ,Num = 2500 ,Type = 'A' ,recid = '123456'
insert #h
select id = 1 ,userid = 'ARMEC1' ,Ref = 'Sale' ,ondate = '02/12/2006' ,Actv
=
'RA' ,Num = 2000 ,Type = 'S' ,recid = '123458'
insert #h
select id = 1 ,userid = 'ARMEC1' ,Ref = 'Sale' ,ondate = '09/23/2005' ,Actv
=
'RA' ,Num = 1500 ,Type = 'S' ,recid = '223458'
insert #h
select id = 3 ,userid = 'CANDUML1' ,Ref = 'Needs' ,ondate = '12/12/2005' ,Ac
tv =
'DS' ,Num = 7500 ,Type = 'A' ,recid = '123459'
insert #h
select id = 4 ,userid = 'CANDUML1' ,Ref = 'Needs' ,ondate = '11/10/2005' ,Ac
tv =
'RA' ,Num = 1300 ,Type = 'A' ,recid = '223456'
-- select * from #h
-- Cal
select id = 2 ,userid = 'CANDUML1' ,Ref = 'Sale' ,ondate = '05/06/2006' ,Ac
tv =
'DS' ,Num = 2500 ,Type = 'S' ,recid = '123457'
into #ca
insert #ca
select id = 6 ,userid = 'CUPPSK1' ,Ref = 'Sale' ,ondate = '04/26/2006' ,Actv
=
'DS' ,Num = 2500 ,Type = 'S' ,recid = '123456'
insert #ca
select id = 1 ,userid = 'ARMEC1' ,Ref = 'Sale' ,ondate = '09/26/2006' ,Actv
=
'RS' ,Num = 2500 ,Type = 'S' ,recid = '123458'
insert #ca
select id = 1 ,userid = 'ARMEC1' ,Ref = 'Sale' ,ondate = '07/02/2006' ,Actv
=
'RA' ,Num = 1200 ,Type = 'S' ,recid = '223459'
insert #ca
select id = 3 ,userid = 'CANDUML1' ,Ref = 'Sale' ,ondate = '06/12/2006' ,Act
v =
'DS' ,Num = 2500 ,Type = 'S' ,recid = '123459'
insert #ca
select id = 4 ,userid = 'CANDUML1' ,Ref = 'Sale' ,ondate = '06/12/2006' ,Act
v =
'RA' ,Num = 2500 ,Type = 'S' ,recid = '223456'
insert #ca
select id = 5 ,userid = 'ARMEC1' ,Ref = 'Sale' ,ondate = '03/26/2006' ,Actv
=
'RA' ,Num = 2500 ,Type = 'S' ,recid = '123458'
-- select * from #ca
-- c1
select id = 2 ,Co = 'Vesto Mays' ,MC = 'Los Angeles' ,Key4 = 'Lora Candum'
,recid = '654322'
into #c1
insert #c1
select id = 1 ,Co = 'Rogers' ,MC = 'Baton' ,Key4 = 'Chaz Arme' ,recid = '654
321'
insert #c1
select id = 3 ,Co = 'Fishy' ,MC = 'Los Angeles' ,Key4 = 'Lora Candum' ,recid
=
'654323'
insert #c1
select id = 4 ,Co = 'Carmers' ,MC = 'Los Angeles' ,Key4 = 'Lora Candum' ,rec
id =
'654324'
insert #c1
select id = 5 ,Co = 'Keys' ,MC = 'Baton' ,Key4 = 'Chaz Arme' ,recid = '65432
5'
insert #c1
select id = 6 ,Co = 'Smartie' ,MC = 'Baton' ,Key4 = 'Kelsy Cupps' ,recid =
'654326'
-- select * from #c1
-- c2
select id = 1 ,uawrv = 3000 ,udsawrv = 20000 ,unewcxd = '07/01/2006' ,udscxd
=
null ,recid = '9876543'
into #c2
insert #c2
select id = 2 ,uawrv = 10000 ,udsawrv = 7000 ,unewcxd = '04/01/2006' ,udscxd
=
null ,recid = '9876543'
insert #c2
select id = 3 ,uawrv = 15000 ,udsawrv = 5000 ,unewcxd = '12/01/2006' ,udscxd
=
null ,recid = '9876543'
insert #c2
select id = 4 ,uawrv = 23000 ,udsawrv = 500 ,unewcxd = '10/12/2006' ,udscxd
=
null ,recid = '9876543'
insert #c2
select id = 5 ,uawrv = 4000 ,udsawrv = 120 ,unewcxd = '02/03/2007' ,udscxd =
null ,recid = '9876543'
insert #c2
select id = 6 ,uawrv = 2500 ,udsawrv = 12000 ,unewcxd = '12/09/2009' ,udscxd
=
null ,recid = '9876543'
-- select * from #c2
-- staff
select id = 2 ,StaffName = 'Lester Mothartes' ,userid = 'MOTHARL1' ,MC = 'Lo
s
Angeles' ,terrid = 2001 ,awrv = 300 ,dsawrv = 2000 ,recid = '654322'
into #s
insert #s
select id = 1 ,StaffName = 'Steve Arme' ,userid = 'ARMES1' ,MC = 'Baton'
,terrid = 2004 ,awrv = 300 ,dsawrv = 2000 ,recid = '654321'
insert #s
select id = 3 ,StaffName = 'Lora Candum' ,userid = 'CANDUML1' ,MC = 'Los
Angeles' ,terrid = 2009 ,awrv = 300 ,dsawrv = 2000 ,recid = '654323'
insert #s
select id = 5 ,StaffName = 'Chaz Arme' ,userid = 'ARMEC1' ,MC = 'Baton' ,te
rrid
= 2005 ,awrv = 300 ,dsawrv = 2000 ,recid = '654325'
insert #s
select id = 6 ,StaffName = 'Kelsy Cupps' ,userid = 'CUPPSK1' ,MC = 'Baton'
,terrid = 2003 ,awrv = 300 ,dsawrv = 2000 ,recid = '654326'
-- select * from #s
declare @.endDate int
set @.endDate = 365
-- ========================================
=====================
select distinct id = c1.id
,Company = c1.co
,MarketCenter = c1.MC
,AE = c1.key4
,AWRV = c2.uawrv
,DSAWRV = c2.udsawrv
,CXD = c2.unewcxd
,DSCXD = c2.udscxd
,caRef
,caRecID
,caOnDate
,haRecType
,haRecID
,haRef
,haLastDate
,hsRecID
,hsRef
,hsLastDate
from #c1 c1 with(nolock)
join #c2 c2 with(nolock) on c1.id = c2.id
-- staff
left join (select staffname ,awrv ,dsawrv ,terrid ,userid from #s with(noloc
k))
s on c1.key4 = s.staffname
-- cal
-- ********** how do I only get the latest **************
join (select id ,caRef = ref ,caRecID = recid ,caOnDate = ondate ,userid fro
m
#ca with(nolock)
where (left(type,1)+left(Actv,1) in('SR','DS') and ondate between getdate()
and getdate()+@.enddate)
) ca on c1.id = ca.id and ca.userid = s.userid
-- ********************** <> **********************
-- hist Appt
left join (select id ,haRef = ref ,haRecID = recid ,haLastDate = ondate
,haRecType = Type from #h with(nolock)
where (left(type,1)+left(ref,5) = 'ANeeds' )) ha on c1.id = ha.id
-- hist Sale
left join (select id ,hsRef = ref ,hsRecID = recid ,hsLastDate = ondate
,hsRecType = Type from #h with(nolock)
where type ='S'
and ondate in(select top 1 ondate from #h with(nolock) where type = 'S' orde
r
by ondate asc)
) hs on c1.id = hs.id
group by c1.id ,c1.co ,c1.MC ,c1.key4 ,c2.uawrv ,c2.udsawrv ,c2.unewcxd
,c2.udscxd
,caRecID ,caOnDate ,haRecType ,haRecID ,haRef
,haLastDate ,hsRecID ,hsRef ,hsLastDate ,caRef
order by id
-- ========================================
=====================
-- clean up
drop table #h
drop table #ca
drop table #c1
drop table #c2
drop table #s
TIA
JeffP....JDP@.Work (JPGMTNoSpam@.sbcglobal.net) writes:
> I would only like to see the latest calendar Sale per #c1 record as
> (select top 1 * from calen order by ondate desc)
> It doesn't matter if it's type is RA or DS, just the latest ONE.
I was not able to get your repro to run, since you use case inconsistently,
and I am running a case-sensitive server.
It was also difficult to under stand the keys, since you did not post
CREATE TABLE statements, only SELECT INTO.
But as I understood it:

> -- ********** how do I only get the latest **************
> join (select id ,caRef = ref ,caRecID = recid ,caOnDate = ondate ,userid
> from
> #ca with(nolock)
> where (left(type,1)+left(Actv,1) in('SR','DS') and ondate between
> getdate()
> and getdate()+@.enddate)
> ) ca on c1.id = ca.id and ca.userid = s.userid
> -- ********************** <> **********************
This was the problematic part. Try replacing the derived table with
this query:
select a.id, caRef = a.ref ,caRecID = a.recid ,caOnDate = a.ondate,
a.userid
from #ca a
JOIN (SELECT id, userid, ondate = MAX(ondate)
FROM #ca
where (left(type,1)+left(Actv,1) in('SR','DS')
and ondate between convert(char(8, getdate(), 112) and
dateadd (DAY, @.enddate, convert(char(8), getdate())
I also rewrite the condition ondate, as it seemed like you like
to incldue today. and assuming that ondate is date-only, comparing
to getdate() which has both date and time is not good.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Erland, sorry to say that this doesn't help... also sorry to hear that you w
ork
on a case sensetive environment
Your supplemental query failed due to a group by clause as well as the "on"
portion of the join.
When I cleaned these items up, I still got a row for each condition just lik
e in
my original but with an additional join.
I'm not sure how to phrase my question, I only want the one row as in "top 1
"
which I had used with an order by clause desc which essentially was the same
as
using max(ondate) without needing a group by.
However when using top 1 in a sub query it appears that the top 1 was is nev
er
found, I'm sure there is a good reason for this, so it doesn't matter.
Still searching...
JeffP...
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns979B6E52A678Yazorman@.127.0.0.1...
> JDP@.Work (JPGMTNoSpam@.sbcglobal.net) writes:
> I was not able to get your repro to run, since you use case inconsistently
,
> and I am running a case-sensitive server.
> It was also difficult to under stand the keys, since you did not post
> CREATE TABLE statements, only SELECT INTO.
> But as I understood it:
>
> This was the problematic part. Try replacing the derived table with
> this query:
> select a.id, caRef = a.ref ,caRecID = a.recid ,caOnDate = a.ondate,
> a.userid
> from #ca a
> JOIN (SELECT id, userid, ondate = MAX(ondate)
> FROM #ca
> where (left(type,1)+left(Actv,1) in('SR','DS')
> and ondate between convert(char(8, getdate(), 112) and
> dateadd (DAY, @.enddate, convert(char(8), getdate()
)
>
> I also rewrite the condition ondate, as it seemed like you like
> to incldue today. and assuming that ondate is date-only, comparing
> to getdate() which has both date and time is not good.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx|||JDP@.Work (JPGMTNoSpam@.sbcglobal.net) writes:
> Erland, sorry to say that this doesn't help... also sorry to hear that
> you work on a case sensetive environment
> Your supplemental query failed due to a group by clause as well as the
> "on" portion of the join.
> When I cleaned these items up, I still got a row for each condition just
> like in my original but with an additional join.
> I'm not sure how to phrase my question, I only want the one row as in
> "top 1" which I had used with an order by clause desc which essentially
> was the same as using max(ondate) without needing a group by.
> However when using top 1 in a sub query it appears that the top 1 was is
> never found, I'm sure there is a good reason for this, so it doesn't
> matter.
It probably helps if you rewrite your repro to use CREATE TABLE with
definition of keys included. It also helps if you include the expected
output. And of course, it's a good idea to clean up inconsistent use of
case. It is a good recommendation to do all development with a case-
sensitive collation, in case this would be a requirement for production.
I took a guess on what the keys would be, but as I could not get the
script to work, I could not test it. And since there was no expected
result, I would not have been able to verify it anyway. I was hoping,
though, that you could use my suggestion as a starting point.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Erland, thank you for your suggestions...
What's happening is that in my test, I am getting expected results but in li
ve I
do not as there are more aspects.
The Fkeys are the ID.
What I want is one row for each record, with the greatest appropriate recid
for
the calendar, history records.
here is my latest, I don't expect in my world to every be in a case sensetiv
e
environment, I just won't do it.
In the following example yields...notice that for record id = 1 whe have two
nearly identical sales, however one has a greater cal ondate, which is now
returned by the final qry.
However in production with real tables, additional fields I still am getting
a
few rows, if you wish to see my real qry send me a pm.
JeffP...
id userid Ref ondate Actv Num Type recid
-- -- -- -- -- -- -- --
1 ARMEC1 SaleR 09/26/2006 RA 2500 S 123458
1 ARMEC1 SaleR 07/02/2006 RA 1200 S 223459
caRecID caRef caOnDate userid id
-- -- -- -- --
123458 SaleR 09/26/2006 ARMEC1 1
id Company MarketCenter AE AWRV DSAWRV CXD
DSCXD caActv caRef caRecID caOnDate hnfRecID hnRef hnLastDate hpRecID
hpRef hpLastDate
-- -- -- -- -- -- --
--
-- -- -- -- -- -- -- -- -- --
--
-- --
1 Rogers Baton Chaz Arme 3000 20000
07/01/2006 01/01/1900 RA SaleR 123458 09/26/2006 123456 Needs 01/26/2
006
NULL NULL NULL
2 Vesto Mays Los Angeles Lora Candum 10000 7000
04/01/2006 01/01/1900 DS SaleD 123457 05/06/2006 123457 Needs 03/06/2
006
NULL NULL NULL
4 Carmers Los Angeles Lora Candum 23000 500
10/12/2006 01/01/1900 RA RA 223456 06/12/2006 223456 Needs 11/10/2
005
NULL NULL NULL
6 Smartie Baton Kelsy Cupps 2500 12000
01/01/1900 01/01/2007 DS Sale 123456 04/26/2006 223457 Needs 11/01/2
005
223459 Propo 11/10/2005
-- begin
set nocount on
-- Hist
select id = 2 ,userid = 'CANDUML1' ,Ref = 'Needs' ,ondate = '03/06/2006' ,Ac
tv =
'DS' ,Num = 500 ,Type = 'A' ,recid = '123457'
into #h
insert #h
select id = 1 ,userid = 'ARMEC1' ,Ref = 'Needs' ,ondate = '01/26/2006' ,Actv
=
'RA' ,Num = 2500 ,Type = 'A' ,recid = '123456'
insert #h
select id = 1 ,userid = 'ARMEC1' ,Ref = 'Sale' ,ondate = '02/12/2006' ,Actv
=
'RA' ,Num = 2000 ,Type = 'S' ,recid = '123458'
insert #h
select id = 1 ,userid = 'ARMEC1' ,Ref = 'First' ,ondate = '09/23/2005' ,Actv
=
'RA' ,Num = 1500 ,Type = 'A' ,recid = '223458'
insert #h
select id = 3 ,userid = 'CANDUML1' ,Ref = 'Needs' ,ondate = '12/12/2005' ,Ac
tv =
'DS' ,Num = 7500 ,Type = 'A' ,recid = '123459'
insert #h
select id = 4 ,userid = 'CANDUML1' ,Ref = 'Needs' ,ondate = '11/10/2005' ,Ac
tv =
'RA' ,Num = 1300 ,Type = 'A' ,recid = '223456'
insert #h
select id = 6 ,userid = 'CUPPSK1' ,Ref = 'Needs' ,ondate = '11/01/2005' ,Act
v =
'RA' ,Num = 1300 ,Type = 'A' ,recid = '223457'
insert #h
select id = 6 ,userid = 'CUPPSK1' ,Ref = 'Propo' ,ondate = '11/10/2005' ,Act
v =
'RA' ,Num = 1300 ,Type = 'A' ,recid = '223459'
-- select * from #h
-- Cal
select id = 2 ,userid = 'CANDUML1' ,Ref = 'SaleD' ,ondate = '05/06/2006' ,A
ctv
= 'DS' ,Num = 2500 ,Type = 'S' ,recid = '123457'
into #ca
insert #ca
select id = 6 ,userid = 'CUPPSK1' ,Ref = 'Sale' ,ondate = '04/26/2006' ,Actv
=
'DS' ,Num = 2500 ,Type = 'S' ,recid = '123456'
insert #ca
select id = 1 ,userid = 'ARMEC1' ,Ref = 'SaleR' ,ondate = '09/26/2006' ,Actv
=
'RA' ,Num = 2500 ,Type = 'S' ,recid = '123458'
insert #ca
select id = 1 ,userid = 'ARMEC1' ,Ref = 'SaleR' ,ondate = '07/02/2006' ,Actv
=
'RA' ,Num = 1200 ,Type = 'S' ,recid = '223459'
-- insert #ca
-- select id = 3 ,userid = 'CANDUML1' ,Ref = 'Sale' ,ondate = '06/12/2006' ,
Actv
= 'DS' ,Num = 2500 ,Type = 'S' ,recid = '123459'
insert #ca
select id = 4 ,userid = 'CANDUML1' ,Ref = 'Sale' ,ondate = '06/12/2006' ,Act
v =
'RA' ,Num = 2500 ,Type = 'S' ,recid = '223456'
insert #ca
select id = 5 ,userid = 'ARMEC1' ,Ref = 'Sale' ,ondate = '03/26/2006' ,Actv
=
'RA' ,Num = 2500 ,Type = 'S' ,recid = '123458'
-- select * from #ca
-- c1
select id = 2 ,Co = 'Vesto Mays' ,MC = 'Los Angeles' ,Key4 = 'Lora Candum'
,recid = '654322'
into #c1
insert #c1
select id = 1 ,Co = 'Rogers' ,MC = 'Baton' ,Key4 = 'Chaz Arme' ,recid = '654
321'
insert #c1
select id = 3 ,Co = 'Fishy' ,MC = 'Los Angeles' ,Key4 = 'Lora Candum' ,recid
=
'654323'
insert #c1
select id = 4 ,Co = 'Carmers' ,MC = 'Los Angeles' ,Key4 = 'Lora Candum' ,rec
id =
'654324'
insert #c1
select id = 5 ,Co = 'Keys' ,MC = 'Baton' ,Key4 = 'Chaz Arme' ,recid = '65432
5'
insert #c1
select id = 6 ,Co = 'Smartie' ,MC = 'Baton' ,Key4 = 'Kelsy Cupps' ,recid =
'654326'
-- select * from #c1
-- c2
select id = 1 ,uawrv = 3000 ,udsawrv = 20000 ,unewcxd = '07/01/2006' ,udscxd
=
'01/01/1900' ,recid = '9876543'
into #c2
insert #c2
select id = 2 ,uawrv = 10000 ,udsawrv = 7000 ,unewcxd = '04/01/2006' ,udscxd
=
'01/01/1900' ,recid = '9876543'
insert #c2
select id = 3 ,uawrv = 15000 ,udsawrv = 5000 ,unewcxd = '12/01/2006' ,udscxd
=
'01/01/1900' ,recid = '9876543'
insert #c2
select id = 4 ,uawrv = 23000 ,udsawrv = 500 ,unewcxd = '10/12/2006' ,udscxd
=
'01/01/1900' ,recid = '9876543'
insert #c2
select id = 5 ,uawrv = 4000 ,udsawrv = 120 ,unewcxd = '02/03/2007' ,udscxd =
'01/01/1900' ,recid = '9876543'
insert #c2
select id = 6 ,uawrv = 2500 ,udsawrv = 12000 ,unewcxd = '01/01/1900' ,udscx
d =
'01/01/2007' ,recid = '9876543'
-- select * from #c2
-- staff
select id = 2 ,StaffName = 'Lester Mothartes' ,userid = 'MOTHARL1' ,MC = 'Lo
s
Angeles' ,terrid = 2001 ,awrv = 300 ,dsawrv = 2000 ,recid = '654322'
into #s
insert #s
select id = 1 ,StaffName = 'Steve Arme' ,userid = 'ARMES1' ,MC = 'Baton'
,terrid = 2004 ,awrv = 300 ,dsawrv = 2000 ,recid = '654321'
insert #s
select id = 3 ,StaffName = 'Lora Candum' ,userid = 'CANDUML1' ,MC = 'Los
Angeles' ,terrid = 2009 ,awrv = 300 ,dsawrv = 2000 ,recid = '654323'
insert #s
select id = 5 ,StaffName = 'Chaz Arme' ,userid = 'ARMEC1' ,MC = 'Baton' ,te
rrid
= 2005 ,awrv = 300 ,dsawrv = 2000 ,recid = '654325'
insert #s
select id = 6 ,StaffName = 'Kelsy Cupps' ,userid = 'CUPPSK1' ,MC = 'Baton'
,terrid = 2003 ,awrv = 300 ,dsawrv = 2000 ,recid = '654326'
-- select * from #s
declare @.endDate int
set @.endDate = 365
-- ========================================
=====================
select distinct id = c1.id
,Company = c1.co
,MarketCenter = c1.MC
,AE = c1.key4
,AWRV = c2.uawrv
,DSAWRV = c2.udsawrv
,CXD = c2.unewcxd
,DSCXD = c2.udscxd
,caActv = (select case when cast(isnull(cab.caOndate,'01/01/1900')as datetime)d">
>= cast(isnull(cad.caOndate,'01/01/1900')as datetime)
and cast(isnull(cab.caOndate,'01/01/1900')as datetime) >=
cast(isnull(car.caOndate,'01/01/1900')as datetime) then cab.Actv
when cast(isnull(cad.caOndate,'01/01/1900')as datetime) >=
cast(isnull(cab.caOndate,'01/01/1900')as datetime)
and cast(isnull(cad.caOndate,'01/01/1900')as datetime) >=
cast(isnull(car.caOndate,'01/01/1900')as datetime) then cad.Actv else car.Ac
tv
end)
,caRef = (select case when cast(isnull(cab.caOndate,'01/01/1900')as datetime
) >=
cast(isnull(cad.caOndate,'01/01/1900')as datetime)
and cast(isnull(cab.caOndate,'01/01/1900')as datetime) >=
cast(isnull(car.caOndate,'01/01/1900')as datetime) then cab.caRef
when cast(isnull(cad.caOndate,'01/01/1900')as datetime) >=
cast(isnull(cab.caOndate,'01/01/1900')as datetime)
and cast(isnull(cad.caOndate,'01/01/1900')as datetime) >=
cast(isnull(car.caOndate,'01/01/1900')as datetime) then cad.caRef else car.
Actv
end)
,caRecID = (select case when cast(isnull(cab.caOndate,'01/01/1900')as datetime)ed">
>= cast(isnull(cad.caOndate,'01/01/1900')as datetime)
and cast(isnull(cab.caOndate,'01/01/1900')as datetime) >=
cast(isnull(car.caOndate,'01/01/1900')as datetime) then cab.caRecID
when cast(isnull(cad.caOndate,'01/01/1900')as datetime) >=
cast(isnull(cab.caOndate,'01/01/1900')as datetime)
and cast(isnull(cad.caOndate,'01/01/1900')as datetime) >=
cast(isnull(car.caOndate,'01/01/1900')as datetime) then cad.caRecID else
car.caRecID end)
,caOnDate = (select case when cast(isnull(cab.caOndate,'01/01/1900')as datetime)red">
>= cast(isnull(cad.caOndate,'01/01/1900')as datetime)
and cast(isnull(cab.caOndate,'01/01/1900')as datetime) >=
cast(isnull(car.caOndate,'01/01/1900')as datetime) then cab.caOndate
when cast(isnull(cad.caOndate,'01/01/1900')as datetime) >=
cast(isnull(cab.caOndate,'01/01/1900')as datetime)
and cast(isnull(cad.caOndate,'01/01/1900')as datetime) >=
cast(isnull(car.caOndate,'01/01/1900')as datetime) then cad.caOndate else
car.caOndate end)
,hnfRecID = (select case when cast(isnull(han.LastDate,'01/01/1900')as
datetime) > cast(isnull(haf.LastDate,'01/01/1900')as datetime)
then han.Recid else haf.Recid end)
,hnRef = (select case when cast(isnull(han.LastDate,'01/01/1900')as datetime
) >
cast(isnull(haf.LastDate,'01/01/1900')as datetime)
then han.Ref else haf.Ref end)
,hnLastDate = (select case when cast(isnull(han.LastDate,'01/01/1900')as
datetime) > cast(isnull(haf.LastDate,'01/01/1900')as datetime)
then han.LastDate else haf.LastDate end)
,hpRecID = (select case when cast(isnull(happ.LastDate,'01/01/1900')as datetime)red">
> cast(isnull(haps.LastDate,'01/01/1900')as datetime)
then happ.recid else haps.recid end)
,hpRef = (select case when cast(isnull(happ.LastDate,'01/01/1900')as datetime)ed">
> cast(isnull(haps.LastDate,'01/01/1900')as datetime)
then happ.ref else haps.ref end)
,hpLastDate = (select case when cast(isnull(happ.LastDate,'01/01/1900')as
datetime) > cast(isnull(haps.LastDate,'01/01/1900')as datetime)
then happ.lastdate else haps.lastdate end)
into #main
from #c1 c1 with(nolock)
join #c2 c2 with(nolock) on c1.id = c2.id
-- staff
left join(select staffname ,awrv ,dsawrv ,terrid ,userid from #s with(nolock
))
s on c1.key4 = s.staffname
-- cal
-- how do I only get the latest
left join (select caRecID = recid ,caRef = ref ,caOnDate = ondate ,userid ,i
d
,Actv from #ca with(nolock)
where (left(type,1)+left(Actv,1) in('SD') and ondate between getdate() and
getdate()+@.enddate)
group by id ,ref ,recid ,ondate ,userid ,Actv ) cad on c1.id = cad.id and
cad.userid = s.userid
left join (select caRecID = recid ,caRef = ref ,caOnDate = max(ondate) ,user
id
,id ,Actv from #ca with(nolock)
where (left(type,1)+left(Actv,1) in('SR') and ondate between getdate() and
getdate()+@.enddate)
group by id ,ref ,recid ,ondate ,userid ,Actv) car on c1.id = car.id and
car.userid = s.userid
left join (select top 1 caRecID = recid ,caRef = ref ,caOnDate = max(ondate)
,userid ,id ,Actv from #ca with(nolock)
where (left(type,1)+left(Actv,1) in('SD','SR') and ondate between getdate()
and getdate()+@.enddate)
group by id ,ref ,recid ,ondate ,userid ,Actv ) cab on c1.id = cab.id and
cab.userid = s.userid
-- hist Appt
left join (select id ,Ref = ref ,RecID ,LastDate = ondate ,Type ,userid from
#h with(nolock)
where (left(type,1)+left(ref,5) = 'AFirst' )) haf on c1.id = haf.id and
haf.userid = s.userid
left join (select id ,Ref = ref ,RecID ,LastDate = ondate ,Type ,userid from
#h with(nolock)
where (left(type,1)+left(ref,5) = 'ANeeds' )) han on c1.id = han.id and
han.userid = s.userid
-- hist proposal
left join (select id ,Ref = ref ,RecID ,LastDate = ondate ,Type ,userid from
#h with(nolock)
where (left(type,1)+left(ref,5) = 'APropo' )) happ on c1.id = happ.id and
happ.userid = s.userid
left join (select id ,Ref = ref ,RecID ,LastDate = ondate ,Type ,userid from
#h with(nolock)
where (left(type,1)+left(ref,5) = 'APrese' )) haps on c1.id = haps.id and
haps.userid = s.userid
order by c1.id
-- ========================================
=====================
select * from #ca where id = 1
-- select * from #h where id = 6
select top 1 caRecID = recid ,caRef = ref ,caOnDate = max(ondate) ,userid ,i
d
from #ca with(nolock)
where (left(type,1)+left(Actv,1) in('SR','SD') and ondate between getdate()
and
getdate()+@.enddate)
group by id ,ref ,recid ,ondate ,userid
delete #main where carecid is null
select * from #main
-- clean up
drop table #h
drop table #ca
drop table #c1
drop table #c2
drop table #s
drop table #main
-- end
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns979B5FA7E9005Yazorman@.127.0.0.1...
> JDP@.Work (JPGMTNoSpam@.sbcglobal.net) writes:
>
> It probably helps if you rewrite your repro to use CREATE TABLE with
> definition of keys included. It also helps if you include the expected
> output. And of course, it's a good idea to clean up inconsistent use of
> case. It is a good recommendation to do all development with a case-
> sensitive collation, in case this would be a requirement for production.
> I took a guess on what the keys would be, but as I could not get the
> script to work, I could not test it. And since there was no expected
> result, I would not have been able to verify it anyway. I was hoping,
> though, that you could use my suggestion as a starting point.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx

How to get this relation(Need Sql Query)?

Hi friends

I have one Table called tblCategory.

I have three Column CatID, CatName, ParentID

I have many records in this Table

CatID CatName ParentID

1 Cat1 0

2 Cat2 1

3 Cat3 1

4 Cat4 2

5 Cat5 2

6 Cat6 0

7 Cat7 6

8 Cat8 6

9 Cat9 7

10 Cat10 7

11 Cat11 8

Here I have Main Category which has ParentID 0 [ Cat1 and Cat6 ]

I Have Sub categories of Cat1 Which has ParentID 1(CatID 1 of Cat1) [ Cat2 and Cat 3 ]

Cat 2 has also sub category with ParentID 2 (CatID 2 of Cat2) [ Cat4 and Cat5]

I want result looks like as

Cat1 Cat6 ->>>>>ParentID 0
- Cat2 -Cat7 ->>>>>ParentID 1(CatID of Root Cat1) and ParentID 6(CatID of Root Cat6)
- - Cat4 - -Cat9 ->>>>>PaerntID 2(CatID of Root Cat2) and ParentID 7(CatID of Root Cat7)
- - Cat5 - -Cat10 ->>>>>PaerntID 2(CatID of Root Cat2) and ParentID 7(CatID of Root Cat7)
- Cat3 -Cat8 -->>>>>ParentID 1(CatID of Root Cat1) and ParentID 6(CatID of Root Cat6)
--No record --Cat11

Can anybody give me solution?

Thanks

See if this article on working out JOIN syntax will help:http://www.mikesdotnetting.com/Article.aspx?ArticleID=72

|||

There are two tables but in my case I have only one table.

|||

impathan:

There are two tables but in my case I have only one table.

So you have. Sorry, I saw the word Relation in the title of your post and thought you were after somerthing else.

Is what you are after something like the threaded view of a discussion board or similar? If so, one solution might be a recursive function. If not, could you explain the logic beind the diagram you have supplied? I can't, for example see the basis on which Cat3 and Cat8 on the penultimate line are related.

|||

impathan:

There are two tables but in my case I have only one table.

You can query a table twice in the same statement and join it to itself. :) You just need to give each usage of the table a different table alias.

how to get this output ?

Hi Everybody,
I have a Table Call Referrals like this
EmpId Cl_Date RefrlNo OptNo
1 NULL 2565 2222
1 01/01/2007 2565 2223
2 01/02/2007 2567 2230
3 01/02/2007 2568 2231
3 01/03/2007 2568 2232
4 NULL 2569 2245
4 NULL 2570 2246

From this table i need to get the Emp Id, Cl_date RefrlNO,OptNo
where EmpId must have repeated more than one time as well as it must have at least one Cl_Date + at least one NULL Cl_Date

after all these requirement satisfy , i need to pick again a row data where Cl_Date Is null ?

So the out put should be like this
EmpId Cl_Date RefrlNo OptNo
1 NULL 2565 2222

how do i do this task ?

any idea ?
regards
suis

Code Snippet

createtable Referrals

(

EmpId int,

Cl_Date datetime,

RefrlNo int,

OptNo int

)

GO

insertinto Referrals values(1,NULL, 2565, 2222)

insertinto Referrals values(1,'01/01/2007', 2565, 2223)

insertinto Referrals values(2,'01/02/2007', 2567, 2230)

insertinto Referrals values(3,'01/02/2007', 2568, 2231)

insertinto Referrals values(3,'01/03/2007', 2568, 2232)

insertinto Referrals values(4,NULL,2569,2245)

insertinto Referrals values(4,NULL,2570,2246)

SELECT EmpId, Cl_date, RefrlNo, OptNo FROM Referrals

WHERE

EmpID IN(select EmpId from Referrals where Cl_date isNULL)

AND

EmpID IN(select EmpId from Referrals where Cl_date isNOTNULL)

AND

Cl_date ISNULL

If for EmpId we have line where Cl_date is NULL (see first IN clause) and line where Cl_Date is not NULL (see second IN clause), its that we have at least two lines with same EmpID

How to get this output

hi their
i create a temp table called tempEmpTran and it content a fileds like
Refrlno Description opt-refno

1474 New 5
1474 followup 3
1474 followup 3
1470 new 7

No my problem is i need to eleminate the refrlno which Description <> 'followup',but again the problem is if i see any referrals which repeating more than once then i need to check if any of that Rrefrlno got any Description which equal to the followup, if yes i need to eliminate the whole Referealno from the list,

Refrlno Description opt-refno
1474 New 5 -should not include same refrlno got followup
1474 followup 3 -should not include same refrlno got followup
1474 followup 3 -should not include same refrlno got followup
1470 new 7 -should include,cos its got description 'new'

so once all these condition satisfied then the output should looks like this

Refrlno Description opt-refno
1470 new 7

Any Idea ?
regards
Nirangatry this:

Code Snippet

select tempEmpTran.*
from tempEmpTran
inner join

(select refrlno, count(*)
from tempEmpTran
group by refrlno
having count(*) > 1) t1
on t1.refrlno = tempEmpTran.refrlno


|||Formatting seems to be screwed on that post, heres the query again:

Code Snippet

select tempEmpTran.*
from tempEmpTran
inner join

(select refrlno, count(*)
from tempEmpTran
group by refrlno
having count(*) > 1) t1
on t1.refrlno = tempEmpTran.refrlno

|||Hi sam,
Many thanks to u r fast respone,but in that query there is not line which eleminate the Description='Followup' ?
any idea ?
regards
Niranga|||Have you ran it?

It only returns records who have a single refrlno... so there shouldn't be any need to filter based on your sample data.

Have a play and try to understand what it does. Then you can expand on it |||

Hey, you could do this 2 ways:

Select *

from tempEmpTran

Where Refrlno not in (Select Refrlno from tempEmpTran where Description = 'Followup')

Select *

from tempEmpTran a

Where not exists (Select Refrlno from tempEmpTran b where Description = 'Followup' and a.Refrlno = b.Refrlno)

BobP

|||Hi i ran a query which u produced me ,but i am getting a error like
"No column was specified for column 2 of 't1'."
i couldn't sort this out ?
any idea ?
regards
niranga|||

Niranga wrote:

Hi i ran a query which u produced me ,but i am getting a error like
"No column was specified for column 2 of 't1'."
i couldn't sort this out ?
any idea ?
regards
niranga

Sorry about that, didn't bother creating the tables and testing. You just need to add an alias to the column name
count(*) becomes
count(*) as [Cnt]|||hi,

here's another alternative.
SELECT *
INTO #tempEmpTran
FROM (
SELECT 1474 AS Refrlno
, 'New' AS Description
, 5 AS [opt-refno]
UNION ALL
SELECT 1474 AS Refrlno
, 'followup' AS Description
, 3 AS [opt-refno]
UNION ALL
SELECT 1474 AS Refrlno
, 'followup' AS Description
, 3 AS [opt-refno]
UNION ALL
SELECT 1470 AS Refrlno
, 'New' AS Description
, 7 AS [opt-refno]
) a

SELECT a.*
FROM #tempEmpTran a INNER JOIN
(
SELECT Refrlno
, IsNew = SUM((CASE WHEN Description = 'New' THEN 0 ELSE 1 END))
FROM #tempEmpTran
GROUP BY
Refrlno
HAVING SUM((CASE WHEN Description = 'New' THEN 0 ELSE 1 END)) = 0
) b ON a.RefrlNo = b.RefrlNo

DROP TABLE #tempEmpTran|||

here you go..

Code Snippet

Create Table #data (

[Refrlno] int ,

[Description] Varchar(100) ,

[opt-refno] int

);

Insert Into #data Values('1474','New','5');

Insert Into #data Values('1474','followup','3');

Insert Into #data Values('1474','followup','3');

Insert Into #data Values('1470','new','7');

Select

*

from

#Data Main

Where

Not Exists

(

Select

Sub.[Refrlno]

From

#Data Sub

Where

Main.[Refrlno]=Sub.[Refrlno]

And Sub.[Description] = 'followup'

)

How to get this out put ?

Hi everybody
I have a requirement like this
I have a table call Child which looks like following

ChildId ChildAgeByYear ReferralSoure NoOfReferral
Ch01 02 Self 2
Ch01 02 Open 1
Ch03 02 Self 1

Now my problem is I need to display the above Child table information like this

AgeGroup ReferralSoure NoOfReferral
0 0
1 0
2 Self 3
Open 1
3 0
4 0

I need to count the child age group by child age like, 1, 2, 3, 4, and their ReferralSource and NoOfReferral for each child depends on the ReferralSource

Any Idea ?

Regards
Suis

Perhaps something like this:

declare @.child table
( ChildId varchar(5),
ChildAgeByYear integer,
ReferralSource varchar(12),
NoOfReferral integer
)
insert into @.child
select 'Ch01', 2, 'Self', 2 union all
select 'Ch01', 2, 'Open', 1 union all
select 'Ch03', 2, 'Self', 1
--select * from @.child

select AgeGroup,
isnull(ReferralSource, '') as ReferralSource,
sum( case when NoOfReferral is null then 0
else NoOfReferral end
) as NoOfReferral
from ( select 0 as AgeGroup union all select 1 union all
select 2 union all select 3 union all select 4
) as n
left join @.child c
on n.AgeGroup = c.ChildAgeByYear
group by AgeGroup,
ReferralSource
order by AgeGroup,
sum( case when NoOfReferral is null then 0
else NoOfReferral end
) desc

/*
AgeGroup ReferralSource NoOfReferral
-- --
0 0
1 0
2 Self 3
2 Open 1
3 0
4 0
*/

|||Thank you very much
4 your quick response,i will let u now the outcome once i test this
best regards
suis

How to get this out put ?


Hi everybody I have a table call Child
and the information like this

ChildId Department Born_Dttm
01 ICU 01/01/2007
02 NormatWard 01/01/2006
03 ICU 01/01/2005

I need to get this out put like i need to count how many child attached to a particular department depending on child age ?

Department < 5 Months > 5Months 1 Year 2Year
ICU 1 0 0 1
NormatWard 0 0 1 0

Age calculation should be up to todays date ?

Any Idea ?
regards
suis

Here are a couple of resources detailing how to do this.

Pivot Tables - How to rotate a table in SQL Server
http://support.microsoft.com/default.aspx?scid=kb;en-us;175574

Pivot Tables -Dynamic Cross-Tabs
http://www.sqlteam.com/item.asp?ItemID=2955

|||Hi Arni
thank you for u r quick response and many thanks to u r link
actually i have learned some thing out of that link and i could produce some SQL
Bellow is my SQL

DECLARE @.Child TABLE

(

[ChildId] varchar(2),

[Department] varchar(10),

[Born_Dttm] varchar(12)

)

INSERT INTO @.Child([ChildId], [Department], [Born_Dttm])

SELECT '01', 'ICU', '01/01/2007' UNION ALL

SELECT '02', 'NormalWard', '01/01/2006' UNION ALL

SELECT '03', 'ICU', '01/01/2005'

select [Department] ,

(select count(datediff(mm,[Born_Dttm],getdate())/12) from @.Child ch1 where datediff(mm,[Born_Dttm],getdate())/12 < 1 AND ch1.[Department]=ch.[Department] ) as ZeroToOneYear,
(select count(datediff(mm,[Born_Dttm],getdate())/12) from @.Child ch2 where datediff(mm,[Born_Dttm],getdate())/12 >= 1 AND datediff(mm,[Born_Dttm],getdate())/12 < 2 AND ch2.[Department]=ch.[Department] ) as OneTOTwoYear,
(select count(datediff(mm,[Born_Dttm],getdate())/12) from @.Child ch2 where datediff(mm,[Born_Dttm],getdate())/12 >= 2 AND datediff(mm,[Born_Dttm],getdate())/12 < 3 AND ch2.[Department]=ch.[Department] ) as TwoTOThreeYear
from @.Child ch
GROUP BY ch.[Department]

Now the problem is i can't get the Months calculation ?
can u help me to get months calculation
like 0 to 5 months ? and 5 to 1 year ?
Any Idea ?
regards
suis|||

This might work more efficiently. (Note the ZeroToOneYear is double counting the Months columns.)

Code Snippet


DECLARE @.Child TABLE
( [ChildId] varchar(2),
[Department] varchar(10),
[Born_Dttm] varchar(12)
)


INSERT INTO @.Child VALUES ( '01', 'ICU', '01/01/2007' )
INSERT INTO @.Child VALUES ( '02', 'NormalWard', '01/01/2006' )
INSERT INTO @.Child VALUES ( '03', 'ICU', '01/01/2005' )

SELECT
[Department],
[Under 5 Months] = sum( CASE WHEN datediff( month, Born_Dttm, getdate() ) < 5 THEN 1 ELSE 0 END ),
[5 MonthsToOneYear] = sum( CASE WHEN datediff( month, Born_Dttm, getdate() ) BETWEEN 5 AND 12 THEN 1 ELSE 0 END ),
[ZeroToOneYear] = sum( CASE datediff( year, Born_Dttm, getdate() ) WHEN 0 THEN 1 ELSE 0 END ),
[OneToTwoYear] = sum( CASE datediff( year, Born_Dttm, getdate() ) WHEN 1 THEN 1 ELSE 0 END ),
[TwoTOThreeYear] = sum( CASE datediff( year, Born_Dttm, getdate() ) WHEN 2 THEN 1 ELSE 0 END )
from @.Child ch
GROUP BY ch.[Department]

Department Under 5 Months 5 MonthsToOneYear ZeroToOneYear OneToTwoYear TwoTOThreeYear
- -- -- - --
ICU 1 0 1 0 1
NormalWard 0 0 0 1 0

|||Try this:

select [Department],

sum(case when age_mos < 5 then 1 else 0 end) as '< 5 months',

sum(case when age_mos > 4 and age_mos < 12 then 1 else 0 end) as '> 5 months',

sum(case when age_mos > 11 and age_mos < 24 then 1 else 0 end) as '1 year',

sum(case when age_mos > 23 then 1 else 0 end) as '2 year'

from

(select [Department], datediff(mm, [Born_Dttm], getdate()) as age_mos

from @.child) as t

group by [Department]

|||Thanks everybody for this valuable comments
now i could manage to sort out with the help of this forum
this is great help for me,
and this is the place to learn ........

many thanks.......to MSDN forum members ..........

regards
suis

How to get this out put !

Hi i have a table call Employee
Emp_Id Area_Code Temp_Tran_Id
02 2CL NULL
02 2CL 01235
03 3NY NULL
03 2CL 1452
08 2CL NULL

I need to get this out put from that table data !

Emp_Id Area_Code Temp_Tran_Id
02 2CL 01235
03 3NY NULL
03 2CL 1452
08 2CL NULL

These are the rules i must follow when getting that out put

Emp_Id and the Area_Code Cannot be repeated same time ,

if it's repeated i need to get the record where Temp_Tran_Id is not null

Any Idea ?

Code Snippet

select Emp_Id, Area_Code, max(Temp_Tran_Id) as TT_Id
from Employee
group by Emp_Id, Area_Code


But what you have to do when there's several records with the same Emp_Id and Area_Code and in some of them Temp_Tran_Id is not null?|||

Perhaps something like this:


declare @.employee table
( Emp_id varchar(5),
Area_Code char(3),
Temp_Tran_Id varchar(12)
)

insert into @.employee
select '02', '2CL', null union all
select '02', '2CL', '01235' union all
select '03', '3NY', null union all
select '03', '2CL', '1452' union all
select '08', '2CL', null

select Emp_id,
Area_code,
max (Temp_Tran_Id) as Temp_Tran_Id
from @.employee
group by Emp_Id,
Area_Code
order by Emp_Id,
max (Temp_Tran_Id), ''

/*
Emp_id Area_code Temp_Tran_Id
02 2CL 01235
03 3NY NULL
03 2CL 1452
08 2CL NULL
*/

|||Thanks very much itsw working perfectly now!
thanks every body
cheers

how to get this out put

Hi i have a table call
EmpTran looks like this
EmpId StDate TranID
1 NULL 124
1 01/01/2007 145
2 01/02/2004 147
3 NULL 7844

i have some condition to apply this table like
i need to get all EmpId where StDate is NULL
But problem is if EmpId get repeated more than onece then i need to check if any of that record has got any StDate if it is then i need to exclude that every record
EmpId StDate TranID
1 NULL 24 -should not include cos same EmpId got StDate in the second row
1 01/01/2007 45 -should not include cos this EmpId got StDate
2 NULL 147 -should include cos StDate IS NULL
2 NULL 187 -should include cos StDate IS NULL
3 NULL 7844 -should include cos he got one row and StDate IS NUL

so once the conditions satisfy output looks like this
EmpId StDate TranID
2 NULL 147
2 NULL 187
3 NULL 7844

Any Idea ?
regards
suis

Maybe something like:

Code Snippet

declare @.mockup table
( EmpId integer,
StDate datetime,
TranID integer
)

insert into @.mockup
select 1, null, 124 union all
select 1, '1/1/7', 145 union all
select 2, null, 147 union all
select 2, null, 187 union all
select 3, null, 7844
--select * from @.mockup

select * from @.mockup a
where StDate is null
and not exists
( select 0 from @.mockup b
where a.EmpId = b.EmpId
and StDate is not null
)

/*

EmpId StDate TranID
-- - --
2 NULL 147
2 NULL 187
3 NULL 7844
*/

|||Hi Kent,
That's a great SQL ,
Thanks very much for u r fast response,still i am in a SQL learing period,
I think in the future i might be able to write my own complex SQL without any problems.
This is a nice forum to learn and sort out problems.

many thanks to Microsoft team,
best regards
suis|||

This should get you your desired output:

Code Snippet


SET NOCOUNT ON


DECLARE @.EmpTran table
( EmpId int,
StDate datetime,
TranID int
)


INSERT INTO @.EmpTran VALUES ( 1, NULL, 24 )
INSERT INTO @.EmpTran VALUES ( 1, '01/01/2007', 45 )
INSERT INTO @.EmpTran VALUES ( 2, NULL, 147 )
INSERT INTO @.EmpTran VALUES ( 2, NULL, 187 )
INSERT INTO @.EmpTran VALUES ( 3, NULL, 7844 )


SELECT *
FROM @.EmpTran
WHERE EmpID IN (SELECT EmpID
FROM @.EmpTran
GROUP BY EmpID
HAVING max( isnull( StDate, 0 ) ) = 0
)


EmpId StDate TranID
-- --
2 NULL 147
2 NULL 187
3 NULL 7844

how to get this into a table?

Hi all,

Can any body please suggest me how to get the result from the following procedure into a table.

sp_help_job @.Execution_status=1

I just cannot get the result from this procedure into a table

Thanking in advance

Jacx

To get the o/p of a sp to a table the table should already be existing. The output columns should match the table structure. if the table exists

then

Insert into Tablename Exec yoursp

Madhu

|||

i will give u a simple solution. now ifu see the o./p of sp_help_job @.Execution_status=1 then u can see that there are many column. So the simple method is , first findout the script for sp_Hlep_job. for that run sp_helptext sp_help_job.When u run this query, u will get the source code of sp_help_job, and u can see the data type or you can make a wrapper which will automatically create a table for u

Madhu

|||

this is the script for the table i created for geting the results

CREATE TABLE [Tbl_JobDET] (
[Job_id] [uniqueidentifier] NULL ,
[Originating_server] [varchar] (255) NULL ,
[Name] [varchar] (255) NULL ,
[enabled] [int] NULL ,
[description] [varchar] (255) NULL ,
[start_step_id] [int] NULL ,
[Category] [varchar] (255) NULL ,
[owner] [varchar] (255) NULL ,
[notify_level_email] [int] NULL ,
[notify_level_netsend] [int] NULL ,
[notify_level_page] [int] NULL ,
[notify_email_operator] [int] NULL ,
[notify_netsend_operator] [int] NULL ,
[delete_level] [int] NULL ,
[date_created] [datetime] NULL ,
[date_modified] [datetime] NULL ,
[Version_number] [int] NULL ,
[last_run_date] [int] NULL ,
[last_run_time] [int] NULL ,
[last_run_outcome] [int] NULL ,
[next_run_date] [int] NULL ,
[next_run_time] [int] NULL ,
[next_run_schedule_id] [int] NULL ,
[current_execution_status] [int] NULL ,
[current_execution_step] [int] NULL ,
[current_retry_attempt] [int] NULL ,
[has_step] [int] NULL ,
[hsa_schedule] [int] NULL ,
[has_target] [int] NULL ,
[type] [int] NULL
) ON [PRIMARY]
GO


and i tried geting the results using this

insert tbl_jobDET
EXEC sp_help_job @.execution_status=1

and this is the Error i got

Server: Msg 8164, Level 16, State 1, Procedure sp_get_composite_job_info, Line 67
An INSERT EXEC statement cannot be nested.

Any suggestions on how can i resolve this error and get the result into the table ?

|||

Jacx,

A possible solution could be creating a linked server pointing to itself (loopback) and using:

select *

into #t

from openquery(Loopback, 'set fmtonly off; exec msdb.dbo.sp_help_job @.execution_status = 1')

go

select *

from #t

go

drop table #t

go

AMB

|||Jacx,

I was looking for the same, and came across this page:

http://www.sqlservercentral.com/forums/shwmessage.aspx?forumid=8&messageid=259078

It contains this suggestion, which works great:

SELECT * INTO #JobInfo
FROM OPENROWSET('sqloledb', 'server=(local);trusted_connection=yes'
, 'set fmtonly off exec msdb.dbo.sp_help_job @.execution_status=4')

You may have to change your connection string or sp_help_job parameters...

how to get this into a table?

Hi all,

Can any body please suggest me how to get the result from the following procedure into a table.

sp_help_job @.Execution_status=1

I just cannot get the result from this procedure into a table

Thanking in advance

Jacx

To get the o/p of a sp to a table the table should already be existing. The output columns should match the table structure. if the table exists

then

Insert into Tablename Exec yoursp

Madhu

|||

i will give u a simple solution. now ifu see the o./p of sp_help_job @.Execution_status=1 then u can see that there are many column. So the simple method is , first findout the script for sp_Hlep_job. for that run sp_helptext sp_help_job.When u run this query, u will get the source code of sp_help_job, and u can see the data type or you can make a wrapper which will automatically create a table for u

Madhu

|||

this is the script for the table i created for geting the results

CREATE TABLE [Tbl_JobDET] (
[Job_id] [uniqueidentifier] NULL ,
[Originating_server] [varchar] (255) NULL ,
[Name] [varchar] (255) NULL ,
[enabled] [int] NULL ,
[description] [varchar] (255) NULL ,
[start_step_id] [int] NULL ,
[Category] [varchar] (255) NULL ,
[owner] [varchar] (255) NULL ,
[notify_level_email] [int] NULL ,
[notify_level_netsend] [int] NULL ,
[notify_level_page] [int] NULL ,
[notify_email_operator] [int] NULL ,
[notify_netsend_operator] [int] NULL ,
[delete_level] [int] NULL ,
[date_created] [datetime] NULL ,
[date_modified] [datetime] NULL ,
[Version_number] [int] NULL ,
[last_run_date] [int] NULL ,
[last_run_time] [int] NULL ,
[last_run_outcome] [int] NULL ,
[next_run_date] [int] NULL ,
[next_run_time] [int] NULL ,
[next_run_schedule_id] [int] NULL ,
[current_execution_status] [int] NULL ,
[current_execution_step] [int] NULL ,
[current_retry_attempt] [int] NULL ,
[has_step] [int] NULL ,
[hsa_schedule] [int] NULL ,
[has_target] [int] NULL ,
[type] [int] NULL
) ON [PRIMARY]
GO


and i tried geting the results using this

insert tbl_jobDET
EXEC sp_help_job @.execution_status=1

and this is the Error i got

Server: Msg 8164, Level 16, State 1, Procedure sp_get_composite_job_info, Line 67
An INSERT EXEC statement cannot be nested.

Any suggestions on how can i resolve this error and get the result into the table ?

|||

Jacx,

A possible solution could be creating a linked server pointing to itself (loopback) and using:

select *

into #t

from openquery(Loopback, 'set fmtonly off; exec msdb.dbo.sp_help_job @.execution_status = 1')

go

select *

from #t

go

drop table #t

go

AMB

|||Jacx,

I was looking for the same, and came across this page:

http://www.sqlservercentral.com/forums/shwmessage.aspx?forumid=8&messageid=259078

It contains this suggestion, which works great:

SELECT * INTO #JobInfo
FROM OPENROWSET('sqloledb', 'server=(local);trusted_connection=yes'
, 'set fmtonly off exec msdb.dbo.sp_help_job @.execution_status=4')

You may have to change your connection string or sp_help_job parameters...

How to get the whole DDL command from EVENT_INSTANCE

Hello,
I try to save the current DDL in a table using the trigger on database ddl
events.
As usual,
DECLARE @.data XML
SET @.data = EVENTDATA()
@.data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(2000)')
How can I extract more then 2000 chars? Should I use a system table or
function to retrieve all the DDL command? I have SPs whith tons of chars...
Thanks,
CatalinHow about, for instance:
@.data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(4000)')
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Catalin NASTAC" <CatalinNASTAC@.discussions.microsoft.com> wrote in message
news:46BD42B9-FA1B-4697-BD7D-2E54F52F4B93@.microsoft.com...
> Hello,
> I try to save the current DDL in a table using the trigger on database ddl
> events.
> As usual,
> DECLARE @.data XML
> SET @.data = EVENTDATA()
> @.data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(2000)')
> How can I extract more then 2000 chars? Should I use a system table or
> function to retrieve all the DDL command? I have SPs whith tons of chars..
.
> Thanks,
> Catalin|||Thanks, but i have SPs with probably 40k chars or more... Neither varchar
(8000) is enough...
"Tibor Karaszi" wrote:

> How about, for instance:
> @.data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(4000)')
>
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> Blog: http://solidqualitylearning.com/blogs/tibor/
>
> "Catalin NASTAC" <CatalinNASTAC@.discussions.microsoft.com> wrote in messag
e
> news:46BD42B9-FA1B-4697-BD7D-2E54F52F4B93@.microsoft.com...
>|||Did you try nvarchar(max)?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Catalin NASTAC" <CatalinNASTAC@.discussions.microsoft.com> wrote in message
news:989EED5F-D2F0-44EB-A43E-A2FB23BB9B5B@.microsoft.com...
> Thanks, but i have SPs with probably 40k chars or more... Neither varchar
> (8000) is enough...
> "Tibor Karaszi" wrote:
>|||Thank you, I had no ideea about (max) implementation on 2K5... (Please, don'
t
tell me that it was also available on SQL 2000...)
I am so deceived about me... After 8 years of SQL I will have to start again
from ABC... Sometimes I am so busy to find complex solutions and I am not
able to see the simplest one.
Thanks again|||> Thank you, I had no ideea about (max) implementation on 2K5... (Please, don'ted">
> tell me that it was also available on SQL 2000...)
The max datatypes are indeed new to 2005. Consider them as replacements for
the less than user
friendly text, ntext and image datatypes.

> I am so deceived about me... After 8 years of SQL I will have to start aga
in
> from ABC... Sometimes I am so busy to find complex solutions and I am not
> able to see the simplest one.
This happens to all of us. :-)
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Catalin NASTAC" <CatalinNASTAC@.discussions.microsoft.com> wrote in message
news:01DD8998-1C93-43E2-AA9A-F82694049866@.microsoft.com...
> Thank you, I had no ideea about (max) implementation on 2K5... (Please, do
n't
> tell me that it was also available on SQL 2000...)
> I am so deceived about me... After 8 years of SQL I will have to start aga
in
> from ABC... Sometimes I am so busy to find complex solutions and I am not
> able to see the simplest one.
> Thanks again

How to get the total time of the records in a table

Hello,

I have one table that has a column called CallDuration. This columns has always the format "1/01/2000 12:01:38 AM". The date part "1/01/2000" I want to discard, and sum the time part to get a total time in my query. How can I do that?

Thxselect datediff(hour,'1/01/2000 12:01:38 AM', '1/01/2000 11:10:38 AM') Hours,
datediff(minute,'1/01/2000 12:01:38 AM', '1/01/2000 11:10:38 AM') % 60 Minutes,
datediff(minute,'1/01/2000 12:01:38 AM', '1/01/2000 11:10:38 AM') TotalMinutes|||select datediff(hour,min(callduration), max(callduration)) Hours,
datediff(minute,min(callduration), max(callduration)) % 60 Minutes,
datediff(minute,min(callduration), max(callduration)) TotalMinutes

Wednesday, March 28, 2012

how to get the sum of the fields ...Very URGENT

hi .. iam having a table with six fields which is holding some values.
there are two branches for a company. now they want to see the two branches values at once . that is sum of the stockin,
sum of the stock out etc...

my table is here...
stockin
stockout
stockinhand
openingstock
unitrate
value.

Now i want to get the sum of these two brancheshi,

in ur table there is no feilds to specify the branch like branch id like that.
if there is baranch id then the query is like this.....

select sum(stockin) as stockinn,sum(stockout) as stockoutt from stack where branchid=1

othere wise can u send me how u identify two differnt branches.

How to get the status?

I have a table with columns c1, c2, c3, c4.

if all nulls or blanks. Status = 0
if c1 assigned but no c2, c3, and c4, then status = 1
if c2 assigned but no c3 and c4, then status = 2
if c3 .. then ..
if c4 .. then ..

I want to have one SQL to get the status like (ignored checking for
blanks here for demo)

SELECT Status = (if not c4 is null then 4
else not c3 is null then 3
else not c2 is null then 2
else not c1 is null then 1
else 0)
FROM mytable.

Thought of using CASE ... WHEN ... but it is only on one colum.

Any better idea.

Thanks

JohnI'm not sure why you believe that CASE can only reference a single
column (admittedly, Books Online shows only single-column examples):

select case
when coalesce(c1,c2,c3,c4) is null then 0
when c1 is not null and c2 is null and c3 is null and c4 is null then
1
when c1 is null and c2 is not null and c3 is null and c4 is null then
2
/* Add other combinations here */
else null end as 'Status'
from
(select null as 'c1', null as 'c2', null as 'c3', null as 'c4'
union all
select 1, null, null, null
union all
select null, 2, null, null) dt

Simonsql

How to get the SQL statement that caused the trigger fire ?

Hi:
Is it possible to grab the full text of the sql statement that caused a
trigger on a table to fire ?
I try to put the DBCC INPUTBUFFER(@.@.SPID) into the 1st line of the
delete trigger, and in Quary analyzer i'm able to see the DBCC
INPUTBUFFER result, but i don't know how to retrieve this result in my
application code (using ADO and ADO.Net).
Please help.
Thanks
JCVoonHi,
why not look at the trigger definition onthe table...that will tell you
under what conditions the trigger will fire....
"jcvoon" wrote:

> Hi:
> Is it possible to grab the full text of the sql statement that caused a
> trigger on a table to fire ?
> I try to put the DBCC INPUTBUFFER(@.@.SPID) into the 1st line of the
> delete trigger, and in Quary analyzer i'm able to see the DBCC
> INPUTBUFFER result, but i don't know how to retrieve this result in my
> application code (using ADO and ADO.Net).
> Please help.
> Thanks
> JCVoon
>

How to get the SQL statement that caused the trigger fire ?

Hi:
Is it possible to grab the full text of the sql statement that caused a
trigger on a table to fire ?
I try to put the DBCC INPUTBUFFER(@.@.SPID) into the 1st line of the
delete trigger, and in Quary analyzer i'm able to see the DBCC
INPUTBUFFER result, but i don't know how to retrieve this result in my
application code (using ADO and ADO.Net).
Please help.
Thanks
JCVoonHi,
why not look at the trigger definition onthe table...that will tell you
under what conditions the trigger will fire....
"jcvoon" wrote:
> Hi:
> Is it possible to grab the full text of the sql statement that caused a
> trigger on a table to fire ?
> I try to put the DBCC INPUTBUFFER(@.@.SPID) into the 1st line of the
> delete trigger, and in Quary analyzer i'm able to see the DBCC
> INPUTBUFFER result, but i don't know how to retrieve this result in my
> application code (using ADO and ADO.Net).
> Please help.
> Thanks
> JCVoon
>

How to Get the SQL Affinity Mask value in Sql 2005, and table that store this info

Hi All

Can u pls tell me How to Get the SQL Affinity Mask value in Sql 2005.

and what is the table/views name that store this info.

for SQL 2000 , we were using following query:

SQLStatement.printf("select c.value from master..sysconfigures c, master..spt_values v,"
"master..syscurconfigs r where v.type = 'C' and v.number = c.config and v.number >= 0 "
"and v.number = r.config and v.name ='affinity mask'");

lErrCode=SQLExecDirect(hStmt,(SQLCHAR*)pszSQLStatement,strlen(pszSQLStatement));

lSQLBindCol(nAffMask);

But With SQL 2005 , we are getting ZERO(0) ROWS SELECTED.

Is there any reason why you can't just exec sp_configure and look at the value for 'affinity mask'?
(you need 'show advanced options' to be turned on for it to show, though)

/Kenneth

How to get the size of a table

Hi
Have anyone know how to get the info. of the size of s table?EXEC sp_spaceused <table name>
--
Jacco Schalkwijk
SQL Server MVP
"cyshang" <anonymous@.discussions.microsoft.com> wrote in message
news:50CC941F-24D0-46DC-905C-93521419A6D8@.microsoft.com...
> Hi,
> Have anyone know how to get the info. of the size of s table?|||hi
sp_spaceused 'table'
Note: It may provide inaccurate output ,therefore try to update statistics.
"cyshang" <anonymous@.discussions.microsoft.com> wrote in message
news:50CC941F-24D0-46DC-905C-93521419A6D8@.microsoft.com...
> Hi,
> Have anyone know how to get the info. of the size of s table?|||To add to Uri's, you can run
"sp_spaceused tablename, true"
command to update the stats and get the size for the table
HTH
--
Ray Higdon MCSE, MCDBA, CCNA
--
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:OkgIhrz3DHA.360@.TK2MSFTNGP12.phx.gbl...
> hi
> sp_spaceused 'table'
> Note: It may provide inaccurate output ,therefore try to update
statistics.
>
> "cyshang" <anonymous@.discussions.microsoft.com> wrote in message
> news:50CC941F-24D0-46DC-905C-93521419A6D8@.microsoft.com...
> > Hi,
> > Have anyone know how to get the info. of the size of s table?
>|||A quick way is to open Enterprise Manager, under View,
click taskpad. On the right is a tab called tables. Open
and enter table name for details.
Don Saluga
>--Original Message--
>Hi,
> Have anyone know how to get the info. of the size of s
table?
>.
>

How to get the size of a table

Hi,
Have anyone know how to get the info. of the size of s table?EXEC sp_spaceused <table name>
Jacco Schalkwijk
SQL Server MVP
"cyshang" <anonymous@.discussions.microsoft.com> wrote in message
news:50CC941F-24D0-46DC-905C-93521419A6D8@.microsoft.com...
quote:

> Hi,
> Have anyone know how to get the info. of the size of s table?
|||hi
sp_spaceused 'table'
Note: It may provide inaccurate output ,therefore try to update statistics.
"cyshang" <anonymous@.discussions.microsoft.com> wrote in message
news:50CC941F-24D0-46DC-905C-93521419A6D8@.microsoft.com...
quote:

> Hi,
> Have anyone know how to get the info. of the size of s table?
|||To add to Uri's, you can run
"sp_spaceused tablename, true"
command to update the stats and get the size for the table
HTH
Ray Higdon MCSE, MCDBA, CCNA
--
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:OkgIhrz3DHA.360@.TK2MSFTNGP12.phx.gbl...
quote:

> hi
> sp_spaceused 'table'
> Note: It may provide inaccurate output ,therefore try to update

statistics.
quote:

>
> "cyshang" <anonymous@.discussions.microsoft.com> wrote in message
> news:50CC941F-24D0-46DC-905C-93521419A6D8@.microsoft.com...
>
sql