Friday, March 30, 2012

query help

Hi,
I want to bring up the following data for groups:
Blue, Red, Green and Yellow.
I have the following view in sql 7 which brings up the data i want, How can
i bring up the data for the other groups within the same query.
SELECT DISTINCT
salesorders.srep, SUM(salesitems.sprice) AS Expr1,
delv.dtaxd
FROM dbo.salesorders INNER JOIN
dbo.salesitems ON
dbo.salesorders.son = dbo.salesitems.sona INNER JOIN
dbo.delvitems ON
dbo.salesorders.son = dbo.delvitems.dord AND
dbo.salesitems.sonitem = dbo.delvitems.ditem INNER JOIN
dbo.delv ON
dbo.delvitems.delvnoa = dbo.delv.delvno
WHERE (dbo.salesorders.srep = 'blue') AND
(dbo.delv.dedate > CONVERT(DATETIME,
'2008-02-01 00:00:00', 102))
GROUP BY dbo.salesorders.srep, dbo.delv.dtaxd
I then need to call this query witin MS Access and use it to output to a
Data sheet.
Thanks
Mohammad
A little more info.
The data i want will look like this as an example:
Team price Date
==== ==== ===
Blue 500 01/01/2008
Green 600 04/02/2008
Yellow 2000 01/02/2008
"mahmad" wrote:

> Hi,
> I want to bring up the following data for groups:
> Blue, Red, Green and Yellow.
> I have the following view in sql 7 which brings up the data i want, How can
> i bring up the data for the other groups within the same query.
> SELECT DISTINCT
> salesorders.srep, SUM(salesitems.sprice) AS Expr1,
> delv.dtaxd
> FROM dbo.salesorders INNER JOIN
> dbo.salesitems ON
> dbo.salesorders.son = dbo.salesitems.sona INNER JOIN
> dbo.delvitems ON
> dbo.salesorders.son = dbo.delvitems.dord AND
> dbo.salesitems.sonitem = dbo.delvitems.ditem INNER JOIN
> dbo.delv ON
> dbo.delvitems.delvnoa = dbo.delv.delvno
> WHERE (dbo.salesorders.srep = 'blue') AND
> (dbo.delv.dedate > CONVERT(DATETIME,
> '2008-02-01 00:00:00', 102))
> GROUP BY dbo.salesorders.srep, dbo.delv.dtaxd
> I then need to call this query witin MS Access and use it to output to a
> Data sheet.
> Thanks
> Mohammad

Query Help

Hi All,
Hoping you might be able to help with this one.
Say I have this layout:
Tbl_People
Person_ID, Name, Address, City, State, Zip.
Tbl_Response
Response_ID, Person_ID, Q_ID (integer)
LU_Questions
Q_ID, Q_Label
So basically I have a lookup table with a bunch of question IDs. What I'm
really looking to get is data in this format:
Person_ID Q_Label1 QLabel2 QLabel3
5 Yes Yes
No
6 No Yes
Yes
Where I have one column for each record in LU_Questions. If a record exists
in Tbl_Response with that Person_ID and Q_ID, then it will return Yes, if
not, then No.
Any idea how I can do this?
James
Can you post sample data to be tested?
"James" <minorkeys@.gmail.com> wrote in message
news:e61Di0nsHHA.4800@.TK2MSFTNGP05.phx.gbl...
> Hi All,
> Hoping you might be able to help with this one.
> Say I have this layout:
> Tbl_People
> Person_ID, Name, Address, City, State, Zip.
> Tbl_Response
> Response_ID, Person_ID, Q_ID (integer)
> LU_Questions
> Q_ID, Q_Label
>
> So basically I have a lookup table with a bunch of question IDs. What I'm
> really looking to get is data in this format:
> Person_ID Q_Label1 QLabel2 QLabel3
> 5 Yes Yes No
> 6 No Yes Yes
> Where I have one column for each record in LU_Questions. If a record
> exists in Tbl_Response with that Person_ID and Q_ID, then it will return
> Yes, if not, then No.
> Any idea how I can do this?
>
|||I'm not sure what format you'd be looking for it in, but something like:
Tbl_People:
Person_ID Name Address City
1 Bob 123 Street Madison
2 John 321 Ave Johnstown
Tbl_Response:
Person_ID Q_ID
1 1
1 2
2 1
2 2
2 4
Tbl_Questions:
Q_ID Q_Label
1 Golf
2 Camping
3 Hiking
4 Fishing
So ultimately I want:
Name OtherMetaData Golf Camping Hiking Fishing
Bob street/city/etc Yes Yes No No
John street/city/etc Yes Yes No Yes
Make sense? But it would need to be dynamic as Tbl_Questions grows.
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:O7%233G2nsHHA.840@.TK2MSFTNGP03.phx.gbl...
> James
> Can you post sample data to be tested?
>
>
> "James" <minorkeys@.gmail.com> wrote in message
> news:e61Di0nsHHA.4800@.TK2MSFTNGP05.phx.gbl...
>
|||On Jun 19, 10:34 am, "James" <minork...@.gmail.com> wrote:
> I'm not sure what format you'd be looking for it in, but something like:
> Tbl_People:
> Person_ID Name Address City
> 1 Bob 123 Street Madison
> 2 John 321 Ave Johnstown
> Tbl_Response:
> Person_ID Q_ID
> 1 1
> 1 2
> 2 1
> 2 2
> 2 4
> Tbl_Questions:
> Q_ID Q_Label
> 1 Golf
> 2 Camping
> 3 Hiking
> 4 Fishing
> So ultimately I want:
> Name OtherMetaData Golf Camping Hiking Fishing
> Bob street/city/etc Yes Yes No No
> John street/city/etc Yes Yes No Yes
> Make sense? But it would need to be dynamic as Tbl_Questions grows.
> "Uri Dimant" <u...@.iscar.co.il> wrote in message
> news:O7%233G2nsHHA.840@.TK2MSFTNGP03.phx.gbl...
>
>
>
>
>
>
>
>
> - Show quoted text -
select
tp.name
, tp.other
, tq.Q_Label
, tr.golf
, tr.camping,
, tr.hiking
, tr.fishing
from tbl_people tp
join (
select person_id
,Q_id
,case when Q_id =1 then 'yes' else 'no' end golf
,case when Q_id =2 then 'yes' else 'no' end Camping
,case when Q_id =3 then 'yes' else 'no' end Hiking
,case when Q_id =4 then 'yes' else 'no' end Fishing
from tbl_response
)as tr on tp.Person_id =tr.Person_id
|||James
> I'm not sure what format you'd be looking for it in, but something like:
That what I meant
create table Tbl_People (Person_ID int, Name varchar(10)
,Address varchar(20), City varchar(20))
insert into Tbl_People values (1,'Bob','123 Street','Madison')
insert into Tbl_People values (2,'John','321 Ave',' Johnstown')
create table Tbl_Response (Person_ID int,Q_ID int)
insert into Tbl_Response values (1,1)
insert into Tbl_Response values (1,2)
insert into Tbl_Response values (2,1)
insert into Tbl_Response values (2,2)
insert into Tbl_Response values (2,4)
create table Tbl_Questions (Q_ID int,Q_Label varchar(10))
insert into Tbl_Questions values (1,'Golf')
insert into Tbl_Questions values (2,'Camping')
insert into Tbl_Questions values (3,'Hiking')
insert into Tbl_Questions values (4,'Fishing')
select Name ,Address, City,max(case when Q_Label ='Golf' then 'yes' else
'no' end) as Golf,
max(case when Q_Label ='Camping' then 'yes' else
'no' end) as Camping,
max(case when Q_Label ='Hiking' then 'yes' else
'no' end) as Hiking,
max(case when Q_Label ='Fishing' then 'yes' else
'no' end) as Fishing
from Tbl_People tp join Tbl_Response tr
on tp.Person_ID=tr.Person_ID
join Tbl_Questions tq on tq.Q_ID=tr.Q_ID
group by Name ,Address, City
"James" <minorkeys@.gmail.com> wrote in message
news:%23Tx7Y6nsHHA.4916@.TK2MSFTNGP04.phx.gbl...
> I'm not sure what format you'd be looking for it in, but something like:
> Tbl_People:
> Person_ID Name Address City
> 1 Bob 123 Street Madison
> 2 John 321 Ave Johnstown
> Tbl_Response:
> Person_ID Q_ID
> 1 1
> 1 2
> 2 1
> 2 2
> 2 4
> Tbl_Questions:
> Q_ID Q_Label
> 1 Golf
> 2 Camping
> 3 Hiking
> 4 Fishing
> So ultimately I want:
> Name OtherMetaData Golf Camping Hiking Fishing
> Bob street/city/etc Yes Yes No No
> John street/city/etc Yes Yes No Yes
> Make sense? But it would need to be dynamic as Tbl_Questions grows.
> "Uri Dimant" <urid@.iscar.co.il> wrote in message
> news:O7%233G2nsHHA.840@.TK2MSFTNGP03.phx.gbl...
>
|||Thank you both. This is pretty close and I may end up having to work with
this.
Is there any way to make the column names dynamic, instead of hardcoded?
Either way thank you immensely for your help.
"schal" <shivaramchalla@.gmail.com> wrote in message
news:1182264456.599338.38270@.w5g2000hsg.googlegrou ps.com...
> On Jun 19, 10:34 am, "James" <minork...@.gmail.com> wrote:
> select
> tp.name
> , tp.other
> , tq.Q_Label
> , tr.golf
> , tr.camping,
> , tr.hiking
> , tr.fishing
> from tbl_people tp
> join (
> select person_id
> ,Q_id
> ,case when Q_id =1 then 'yes' else 'no' end golf
> ,case when Q_id =2 then 'yes' else 'no' end Camping
> ,case when Q_id =3 then 'yes' else 'no' end Hiking
> ,case when Q_id =4 then 'yes' else 'no' end Fishing
> from tbl_response
> )as tr on tp.Person_id =tr.Person_id
>
sql

Query Help

Hi all,
I have one ‘tall’ table that records the following on a regular basis:
STATE SERIAL# DATE
====== ======== ========
VA Z32WE12 12/31/2003
CA QWEFD1 05/04/2005
VA Z32WE13 01/01/2003
CA QWEFD2 05/05/2005
TX POISD21 05/03/2005
TX POISD21 05/04/2005
TX POISD21 05/05/2005
We are tracking the serial number for each state and would like to report on
the current and previous serial number for each state. Can someone please
help me with building the query in order to get the following:
StateCurrent Serial#SincePrevious Serial#
CAQWEFD205/05/2005QWEFD1
VAZ32WE1301/01/2003Z32WE12
TXPOISD21 05/03/2005 Never Changed
Thanks in advance,
-Appreciator
It seems to be a flaw in the data:

> VA Z32WE12 12/31/2003
> VA Z32WE13 01/01/2003
Did you mean "12/31/2002" for serial# "Z32WE12"?
try:
use northwind
go
create table t1 (
state char(2) not null,
serial# varchar(10) not null,
[date] datetime,
)
go
insert into t1 values('VA','Z32WE12', '12/31/2002')
insert into t1 values('CA','QWEFD1' , '05/04/2005')
insert into t1 values('VA','Z32WE13', '01/01/2003')
insert into t1 values('CA','QWEFD2' , '05/05/2005')
insert into t1 values('TX','POISD21', '05/03/2005')
insert into t1 values('TX','POISD21', '05/04/2005')
insert into t1 values('TX','POISD21', '05/05/2005')
go
create view v1
as
select state, serial#, max([date]) as [date] from t1 group by state, serial#
go
create view v2
as
select
a.state,
a.serial# as current_serial#,
a.[date] as since,
isnull(cast(b.serial# as varchar(25)), 'have_not_changed_since') as
previous_serail#
from
v1 as a
left join
v1 as b
on a.state = b.state and a.[date] = (select min(c.[date]) from v1 as c
where c.state = a.state and c.[date] > b.[date])
go
select
*
from
v2 as a
where
previous_serail# != 'have_not_changed_since'
or (previous_serail# = 'have_not_changed_since' and not exists(select *
from v2 as b where b.state = a.state and b.previous_serail# !=
'have_not_changed_since'))
order by
case when previous_serail# = 'have_not_changed_since' then 1 else 0 end,
a.state
go
drop view v2, v1
go
drop table t1
go
AMB
"URG" wrote:

> Hi all,
> I have one ‘tall’ table that records the following on a regular basis:
> STATE SERIAL# DATE
> ====== ======== ========
> VA Z32WE12 12/31/2003
> CA QWEFD1 05/04/2005
> VA Z32WE13 01/01/2003
> CA QWEFD2 05/05/2005
> TX POISD21 05/03/2005
> TX POISD21 05/04/2005
> TX POISD21 05/05/2005
> We are tracking the serial number for each state and would like to report on
> the current and previous serial number for each state. Can someone please
> help me with building the query in order to get the following:
> StateCurrent Serial#SincePrevious Serial#
> CAQWEFD205/05/2005QWEFD1
> VAZ32WE1301/01/2003Z32WE12
> TXPOISD21 05/03/2005 Never Changed
> Thanks in advance,
> -Appreciator
>
|||Hi Alejandro,
Thanks a bunch! That really works perfect..!!
Sorry about the flaw - I had typed in the sample data.
URG
"Alejandro Mesa" wrote:
[vbcol=seagreen]
> It seems to be a flaw in the data:
>
> Did you mean "12/31/2002" for serial# "Z32WE12"?
> try:
> use northwind
> go
> create table t1 (
> state char(2) not null,
> serial# varchar(10) not null,
> [date] datetime,
> )
> go
> insert into t1 values('VA','Z32WE12', '12/31/2002')
> insert into t1 values('CA','QWEFD1' , '05/04/2005')
> insert into t1 values('VA','Z32WE13', '01/01/2003')
> insert into t1 values('CA','QWEFD2' , '05/05/2005')
> insert into t1 values('TX','POISD21', '05/03/2005')
> insert into t1 values('TX','POISD21', '05/04/2005')
> insert into t1 values('TX','POISD21', '05/05/2005')
> go
> create view v1
> as
> select state, serial#, max([date]) as [date] from t1 group by state, serial#
> go
> create view v2
> as
> select
> a.state,
> a.serial# as current_serial#,
> a.[date] as since,
> isnull(cast(b.serial# as varchar(25)), 'have_not_changed_since') as
> previous_serail#
> from
> v1 as a
> left join
> v1 as b
> on a.state = b.state and a.[date] = (select min(c.[date]) from v1 as c
> where c.state = a.state and c.[date] > b.[date])
> go
> select
> *
> from
> v2 as a
> where
> previous_serail# != 'have_not_changed_since'
> or (previous_serail# = 'have_not_changed_since' and not exists(select *
> from v2 as b where b.state = a.state and b.previous_serail# !=
> 'have_not_changed_since'))
> order by
> case when previous_serail# = 'have_not_changed_since' then 1 else 0 end,
> a.state
> go
> drop view v2, v1
> go
> drop table t1
> go
>
> AMB
> "URG" wrote:

Query Help

Help, please!
I have 3 columns with numeric values. i want to write a query that returns
the following:
If all 3 columns are populated, then the middle value (not the average);
If one colunn has a null, then the lesser value,
If 2 are null, then the remaining value.
For example: if ColumnA = 5 and ColumnB = 10 and ColumnC = 12, then I want
the result to be "10". If ColumnB were null, then the result would be "5".
Making sense?
Is there a way to do this, without having to create a bazillion Case When
statements? (case when columnA > ColumnB and ColumnB < ColumnC then ColumnB
else case when columA < ColumnB and ColumnB > ColumnC then ColumnB else . .
... and so on).
Just wondering.
Thank you!
Kyra
Financial Systems Analyst
CCNA, MCSE, MCSA, MCDBA
Kyra,
I think the bazillion CASEs is the only way to go. Here's one attempt:
CREATE TABLE T1 (T1ID INT NOT NULL IDENTITY, Col1 int, Col2 int, Col3 int)
GO
INSERT T1 VALUES (NULL, NUll, 1)
INSERT T1 VALUES (NULL, 2, NULL)
INSERT T1 VALUES (3, NUll, NULL)
INSERT T1 VALUES (NULL, 4, 5)
INSERT T1 VALUES (6, NULL, 7)
INSERT T1 VALUES (8,9, NULL)
INSERT T1 VALUES (10,11,12)
GO
SELECT
CASE
WHEN Col1 IS NULL AND Col2 IS NULL THEN Col3
WHEN Col2 IS NULL AND Col2 IS NULL THEN Col1
WHEN Col1 IS NULL AND Col3 IS NULL THEN Col2
WHEN Col1 IS NULL AND Col2 IS NOT NULL AND Col3 IS NOT NULL THEN
CASE WHEN Col2 < Col3 THEN Col2 Else Col3 END
WHEN Col2 IS NULL AND Col1 IS NOT NULL AND Col3 IS NOT NULL THEN
CASE WHEN Col1 < Col3 THEN Col1 Else Col3 END
WHEN Col3 IS NULL AND Col1 IS NOT NULL AND Col2 IS NOT NULL THEN
CASE WHEN Col1 < Col2 THEN Col1 Else Col2 END
WHEN Col1 <= Col2 AND Col2 <= Col3 THEN Col2
WHEN Col2 <= Col3 AND Col3 <= Col1 THEN Col3
WHEN Col3 <= Col1 AND Col1 <= Col2 THEN Col1
END
FROM T1
One thing your conditions left out: what if they're all NULL?
Hope this helps,
Ron
Ron Talmage
SQL Server MVP
"Ysandre" <Ysandre@.discussions.microsoft.com> wrote in message
news:3147EC21-B5A3-4725-B156-6A40834E5561@.microsoft.com...
> Help, please!
> I have 3 columns with numeric values. i want to write a query that returns
> the following:
> If all 3 columns are populated, then the middle value (not the average);
> If one colunn has a null, then the lesser value,
> If 2 are null, then the remaining value.
> For example: if ColumnA = 5 and ColumnB = 10 and ColumnC = 12, then I want
> the result to be "10". If ColumnB were null, then the result would be "5".
> Making sense?
> Is there a way to do this, without having to create a bazillion Case When
> statements? (case when columnA > ColumnB and ColumnB < ColumnC then
> ColumnB
> else case when columA < ColumnB and ColumnB > ColumnC then ColumnB else .
> .
> .. and so on).
> Just wondering.
> Thank you!
> Kyra
> --
> Financial Systems Analyst
> CCNA, MCSE, MCSA, MCDBA
|||Ysandre,
Here is an alternative to Ron's solution. In general, you
would have an easier time if all the values were in one
column..
SELECT
T1ID,
CASE cntC
WHEN 1 THEN maxC
WHEN 2 THEN minC
WHEN 3 THEN sumC - maxC - minC
END AS C
FROM (
SELECT
T1ID,
SUM(C) as sumC,
MIN(C) as minC,
MAX(C) as maxC,
COUNT(C) as cntC
FROM (
SELECT T1ID, Col1 AS C FROM T1
UNION ALL
SELECT T1ID, Col2 FROM T1
UNION ALL
SELECT T1ID, Col3 FROM T1
) T
GROUP BY T1ID
) T
or
SELECT T1ID, MIN(C) FROM (
SELECT T1ID, Col1 AS C FROM T1
UNION ALL
SELECT T1ID, Col2 FROM T1
UNION ALL
SELECT T1ID, Col3 FROM T1
) T1
WHERE C IN (
SELECT TOP 2 C FROM (
SELECT T1ID, Col1 AS C FROM T1
UNION ALL
SELECT T1ID, Col2 FROM T1
UNION ALL
SELECT T1ID, Col3 FROM T1
) AS T1x
WHERE T1x.T1ID = T1.T1ID
AND C IS NOT NULL
ORDER BY C DESC
)
GROUP BY T1ID
If your table were in the form I used for the derived table above (one
value column instead of three), you could write
SELECT T1ID, MIN(C) FROM T1
WHERE C IN (
SELECT TOP 2 C FROM T1 AS T1x
WHERE T1x.T1ID = T1.T1ID
AND C IS NOT NULL
ORDER BY C DESC
)
GROUP BY T1ID
Steve Kass
Drew University
Ysandre wrote:

>Help, please!
>I have 3 columns with numeric values. i want to write a query that returns
>the following:
>If all 3 columns are populated, then the middle value (not the average);
>If one colunn has a null, then the lesser value,
>If 2 are null, then the remaining value.
>For example: if ColumnA = 5 and ColumnB = 10 and ColumnC = 12, then I want
>the result to be "10". If ColumnB were null, then the result would be "5".
>Making sense?
>Is there a way to do this, without having to create a bazillion Case When
>statements? (case when columnA > ColumnB and ColumnB < ColumnC then ColumnB
>else case when columA < ColumnB and ColumnB > ColumnC then ColumnB else . .
>.. and so on).
>Just wondering.
>Thank you!
>Kyra
>
>
|||Thank you Ron and Steve, that was very helpful!!!!
Thanks,
ysandre
"Steve Kass" wrote:

> Ysandre,
> Here is an alternative to Ron's solution. In general, you
> would have an easier time if all the values were in one
> column..
> SELECT
> T1ID,
> CASE cntC
> WHEN 1 THEN maxC
> WHEN 2 THEN minC
> WHEN 3 THEN sumC - maxC - minC
> END AS C
> FROM (
> SELECT
> T1ID,
> SUM(C) as sumC,
> MIN(C) as minC,
> MAX(C) as maxC,
> COUNT(C) as cntC
> FROM (
> SELECT T1ID, Col1 AS C FROM T1
> UNION ALL
> SELECT T1ID, Col2 FROM T1
> UNION ALL
> SELECT T1ID, Col3 FROM T1
> ) T
> GROUP BY T1ID
> ) T
> or
> SELECT T1ID, MIN(C) FROM (
> SELECT T1ID, Col1 AS C FROM T1
> UNION ALL
> SELECT T1ID, Col2 FROM T1
> UNION ALL
> SELECT T1ID, Col3 FROM T1
> ) T1
> WHERE C IN (
> SELECT TOP 2 C FROM (
> SELECT T1ID, Col1 AS C FROM T1
> UNION ALL
> SELECT T1ID, Col2 FROM T1
> UNION ALL
> SELECT T1ID, Col3 FROM T1
> ) AS T1x
> WHERE T1x.T1ID = T1.T1ID
> AND C IS NOT NULL
> ORDER BY C DESC
> )
> GROUP BY T1ID
> If your table were in the form I used for the derived table above (one
> value column instead of three), you could write
> SELECT T1ID, MIN(C) FROM T1
> WHERE C IN (
> SELECT TOP 2 C FROM T1 AS T1x
> WHERE T1x.T1ID = T1.T1ID
> AND C IS NOT NULL
> ORDER BY C DESC
> )
> GROUP BY T1ID
> Steve Kass
> Drew University
>
> Ysandre wrote:
>

Query help

Here is what I am trying to do... I have a phone list of all our stores. It
contains managers home and cell numbers for emergencies. So the list is
about 44 stores and about 7 to 8 managers to each store...so that's about
350 or so numbers on this list... Now our store each have there own unique
IP address, ex. Store 2 would be 192.168.2.? So within the phone list I
have, for each store I have stored the Ip like 192.168.2 or 192.168.6 and
so on.. Well what I want to do is try to build a query that will only return
records that are similar to the users IP... so I have a hidden request for
the IP... Request.ServerVariables("REMOTE_ADDR") which I want to use as a
variable in my query to compare their ip with what's in the table..
So the results would be like this...
My IP 192.168.6.15
I should see ONLY records with 192.168.6 as part of the IP.
Any suggestions? Ideas? not sure if this would be the place to post this,
but would appreciate any help.
You might want to try the LIKE operator, read more in Books Online.
Regards,
Eric Garza
AMIGE
"Daniel_Cha" <dan_cha@.hotmail.com> wrote in message
news:uRdrbBByEHA.1404@.TK2MSFTNGP11.phx.gbl...
> Here is what I am trying to do... I have a phone list of all our stores.
It
> contains managers home and cell numbers for emergencies. So the list is
> about 44 stores and about 7 to 8 managers to each store...so that's about
> 350 or so numbers on this list... Now our store each have there own unique
> IP address, ex. Store 2 would be 192.168.2.? So within the phone list I
> have, for each store I have stored the Ip like 192.168.2 or 192.168.6 and
> so on.. Well what I want to do is try to build a query that will only
return
> records that are similar to the users IP... so I have a hidden request for
> the IP... Request.ServerVariables("REMOTE_ADDR") which I want to use as a
> variable in my query to compare their ip with what's in the table..
> So the results would be like this...
> My IP 192.168.6.15
> I should see ONLY records with 192.168.6 as part of the IP.
> Any suggestions? Ideas? not sure if this would be the place to post this,
> but would appreciate any help.
>
|||Daniel_Cha wrote:
> Here is what I am trying to do... I have a phone list of all our
> stores. It contains managers home and cell numbers for emergencies.
> So the list is about 44 stores and about 7 to 8 managers to each
> store...so that's about 350 or so numbers on this list... Now our
> store each have there own unique IP address, ex. Store 2 would be
> 192.168.2.? So within the phone list I have, for each store I have
> stored the Ip like 192.168.2 or 192.168.6 and so on.. Well what I
> want to do is try to build a query that will only return records that
> are similar to the users IP... so I have a hidden request for the
> IP... Request.ServerVariables("REMOTE_ADDR") which I want to use as a
> variable in my query to compare their ip with what's in the table..
> So the results would be like this...
> My IP 192.168.6.15
> I should see ONLY records with 192.168.6 as part of the IP.
> Any suggestions? Ideas? not sure if this would be the place to post
> this, but would appreciate any help.
It sounds like your IP address is stored in character format, and that's
good. To select only those stores that match your specs, use:
Select store_information
From Stores
Where IP LIKE '192.168.6.%'
Or if you are using a parameter:
@.IP as varchar(12)
Set @.IP = @.IP + '%'
Select store_information
From Stores
Where IP LIKE @.IP
David Gugick
Imceda Software
www.imceda.com
|||ok, here is my sql statement...
SELECT *
FROM tbEmerStore, tbIpRange
WHERE tbEmerStore.Store = tbIpRange.StoreNum AND tbIpRange.IpRange LIKE
'varIP'
ORDER BY Store
Variable is Name= varIP Run-Time Value =
Request.ServerVariable("REMOTE_ADDR")
what am i doing wrong?
"David Gugick" <davidg-nospam@.imceda.com> wrote in message
news:%23fMvpGByEHA.2540@.TK2MSFTNGP09.phx.gbl...
> Daniel_Cha wrote:
> It sounds like your IP address is stored in character format, and that's
> good. To select only those stores that match your specs, use:
> Select store_information
> From Stores
> Where IP LIKE '192.168.6.%'
> Or if you are using a parameter:
> @.IP as varchar(12)
> Set @.IP = @.IP + '%'
> Select store_information
> From Stores
> Where IP LIKE @.IP
>
> --
> David Gugick
> Imceda Software
> www.imceda.com
>
|||Daniel_Cha wrote:
> ok, here is my sql statement...
> SELECT *
> FROM tbEmerStore, tbIpRange
> WHERE tbEmerStore.Store = tbIpRange.StoreNum AND tbIpRange.IpRange
> LIKE 'varIP'
> ORDER BY Store
> Variable is Name= varIP Run-Time Value =
> Request.ServerVariable("REMOTE_ADDR")
> what am i doing wrong?
>
You are not using a variable. You are using the literal 'varIP'. 'varIP'
is not a variable.
Also, you should never use SELECT * in a production environment. It's
considered bad practice because you almost always end up returning more
columns than you really need. Even if you need them all, specify each
one in the query.
Review my example again.
David Gugick
Imceda Software
www.imceda.com
|||I'm assuming that the varIP is storing the full octets, what does the
tbIpRane.IpRange field data look like?
I'm also assuming you are sending ad hoc T-SQL to the server instead of
using a stored procedure. I'll also assume that you are only storing the
truncated octet in the database. If this is so, modify your query, thusly:
varSQL = "
SELECT *
FROM tbEmerStore AS es
INNER JOIN
tbIpRange AS ir
ON es.Store = ir.StoreNum
WHERE ir.IpRange = " & LEFT(varIP, 12) & "
ORDER BY es.Store
"
conn.Execute(varSQL)
This is probably not exact given the line breaks, but you should be able to
get the point.
To make life easier, I would strongly recommend that you use fixed-length,
zero-padded IP addresses and subnets; otherwise, you are going to have to do
some INSTR pattern matching to find the last "." octet seperator to determine
if the characters you need to truncate is 1, 2, or 3--that would suck.
Sincerely,
Anthony Thomas
"Daniel_Cha" wrote:

> ok, here is my sql statement...
> SELECT *
> FROM tbEmerStore, tbIpRange
> WHERE tbEmerStore.Store = tbIpRange.StoreNum AND tbIpRange.IpRange LIKE
> 'varIP'
> ORDER BY Store
> Variable is Name= varIP Run-Time Value =
> Request.ServerVariable("REMOTE_ADDR")
> what am i doing wrong?
>
>
> "David Gugick" <davidg-nospam@.imceda.com> wrote in message
> news:%23fMvpGByEHA.2540@.TK2MSFTNGP09.phx.gbl...
>
>
|||Ok, I what is stored in the database is the following:
Table = tbIpRange
Column Name Value
StoreNum 02 San Antonio
IPRange 192.168.2
Table = tbEmerStore
Column Name Value
Store 02 San Antonio
So I have one table that contains this information for each store, since
this will not change unless we add a new location to the company.
In the table that contains all the information there is a column that
contains the same StoreNum value and its called Store
So my select statement looks like this..
SELECT Store, StoreNum
FROM tbEmerStore, tbIpRange
WHERE tbEmerStore.Store = tbIpRange.StoreNum AND 'varIP' LIKE
tbIpRange.IpRange
my variable varIP has a run-time value of
Request.ServerVariable("REMOTE_ADDR") so that I can capture the users IP
and compare it to the table.
Im not all that great with queries and variables... so im not sure what im
doing wrong...and our SQL guru is out on vacation since he just had a little
boy this week.. so I dont have anyone to help me with this. So I want to
compare the REMOTE_ADDR to the IPRange column.. and if they are alike then
ONLY return the stores that have that IP Range.
"AnthonyThomas" <AnthonyThomas@.discussions.microsoft.com> wrote in message
news:89C657FA-CA4F-4C8C-BF08-3C9447F6C1B5@.microsoft.com...
> I'm assuming that the varIP is storing the full octets, what does the
> tbIpRane.IpRange field data look like?
> I'm also assuming you are sending ad hoc T-SQL to the server instead of
> using a stored procedure. I'll also assume that you are only storing the
> truncated octet in the database. If this is so, modify your query,
thusly:
> varSQL = "
> SELECT *
> FROM tbEmerStore AS es
> INNER JOIN
> tbIpRange AS ir
> ON es.Store = ir.StoreNum
> WHERE ir.IpRange = " & LEFT(varIP, 12) & "
> ORDER BY es.Store
> "
> conn.Execute(varSQL)
> This is probably not exact given the line breaks, but you should be able
to
> get the point.
> To make life easier, I would strongly recommend that you use fixed-length,
> zero-padded IP addresses and subnets; otherwise, you are going to have to
do
> some INSTR pattern matching to find the last "." octet seperator to
determine[vbcol=seagreen]
> if the characters you need to truncate is 1, 2, or 3--that would suck.
> Sincerely,
>
> Anthony Thomas
> "Daniel_Cha" wrote:
that[vbcol=seagreen]
a[vbcol=seagreen]
that's[vbcol=seagreen]
|||I don't mean to give you too much trouble but what are you, dense?
Three of us have given you examples now. Your problem is two-fold.
1. You can't quote your variable: 'varIP'
2. Your source is longer than your search. You'll have to truncate part of
your source.
Look at the examples again.
Sincerely,
Anthony Thomas

"Daniel_Cha" <dan_cha@.hotmail.com> wrote in message
news:%23zj3AaCyEHA.3976@.TK2MSFTNGP09.phx.gbl...
> Ok, I what is stored in the database is the following:
> Table = tbIpRange
> Column Name Value
> StoreNum 02 San Antonio
> IPRange 192.168.2
> Table = tbEmerStore
> Column Name Value
> Store 02 San Antonio
>
> So I have one table that contains this information for each store, since
> this will not change unless we add a new location to the company.
> In the table that contains all the information there is a column that
> contains the same StoreNum value and its called Store
> So my select statement looks like this..
> SELECT Store, StoreNum
> FROM tbEmerStore, tbIpRange
> WHERE tbEmerStore.Store = tbIpRange.StoreNum AND 'varIP' LIKE
> tbIpRange.IpRange
> my variable varIP has a run-time value of
> Request.ServerVariable("REMOTE_ADDR") so that I can capture the users IP
> and compare it to the table.
> Im not all that great with queries and variables... so im not sure what im
> doing wrong...and our SQL guru is out on vacation since he just had a
little
> boy this week.. so I dont have anyone to help me with this. So I want to
> compare the REMOTE_ADDR to the IPRange column.. and if they are alike
then[vbcol=seagreen]
> ONLY return the stores that have that IP Range.
>
>
> "AnthonyThomas" <AnthonyThomas@.discussions.microsoft.com> wrote in message
> news:89C657FA-CA4F-4C8C-BF08-3C9447F6C1B5@.microsoft.com...
the[vbcol=seagreen]
> thusly:
> to
fixed-length,[vbcol=seagreen]
to[vbcol=seagreen]
> do
> determine
LIKE[vbcol=seagreen]
emergencies.[vbcol=seagreen]
have[vbcol=seagreen]
> that
as[vbcol=seagreen]
> a
table..[vbcol=seagreen]
post
> that's
>

Query help

I am sure this is something totally simple that I am forgetting, but
it is driving me crazy!
I have a cross-reference table of items and attributes. So each row
of the table contains one item and one attribute. Most items have
many lines. I need a select statement (or statements) where I can get
back all the items that have 3 specific attributes. So it would be an
AND thing, not an OR thing. How do I do this?
Thanks,
Gala
Please post your DDL. Perhaps relational division will do it:
select
ItemID
from
MyTable
where
attribute in ('ATTR1', 'ATTR2', 'ATTR3')
group by
ItemID
having
count (*) = 3
Tom
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinnaclepublishing.com/sql
"Gala" <gala@.sonic.net> wrote in message
news:14dba7aa.0408231103.5df59f81@.posting.google.c om...
I am sure this is something totally simple that I am forgetting, but
it is driving me crazy!
I have a cross-reference table of items and attributes. So each row
of the table contains one item and one attribute. Most items have
many lines. I need a select statement (or statements) where I can get
back all the items that have 3 specific attributes. So it would be an
AND thing, not an OR thing. How do I do this?
Thanks,
Gala

query help

I will try to be brief
I have two tables I am trying to join that share a foreign key.
the structures are:
table a: column table b: columns
foreign key employee ID employeeID
status earnings
effectivedate checkdate
each table can have multiple rows with the same employee ID. Table b can have multiple rows with the same checkdate. I am trying to query the two tables so I can get the sum of the earnings for a particular checkdate and the employees status at the time
of the check. Here is an example of the data and what I have written so far:
tableA:
employeeID STATUS Effectivedate
100 fulltime 01/01/03
100 parttime 01/01/04
100 fulltime 03/27/04
101 fulltime 01/01/03
101 parttime 04/01/04
tableB:
employeeID earnings checkdate
100 25.00 03/25/04
100 97.00 03/25/04
101 10.00 03/25/04
If I query with the employeeID it is no problem:
select tableB.employeeID, STATUS, Effectivedate, sum(earnings), checkdate
from tableA, tableB
where tableA.employeeID=tableB.employeeID
and effectivedate=(select max(effectivedate) from tableA where tableA.employeeID=100 and effectivdate <='03/25/04')
and checkdate='03/25/04'
group by tableB.employeeID, STATUS, Effectivedate, checkdate
but... to do this on my tables which have thousands and thousands of rows for each ID each month will be painful.
How can I write this query so that the select will return the sum of earnings by employeeID on a specific checkdate and the employee status on that date. I thought of using a cursor, but I am not advanced enough to write one. I am sure there has to be a
way to do this. Any help will be greatly appreciated!!!!
I realize I should have posted this in data mining, but I don't want to double post
sql

query help

I want to find days when people either haven't entered at least 8 hours of
time or days where they haven't entered time at all.
If I select out of the table that holds the time I can get days where they
haven't entered at least 8 hours (i.e. select emp_hours from emp_time where
emp_hours < 8). But how do I also get days where time hasn't been entered
since those days won't be in the table?
Thanks,
Dan D.
Create a calendar table and do an outer join against that table. Some info on calendar tables:
http://www.aspfaq.com/show.asp?id=2519
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Dan D." <DanD@.discussions.microsoft.com> wrote in message
news:BED0D9F5-2515-4A14-B902-B2334EF59A57@.microsoft.com...
>I want to find days when people either haven't entered at least 8 hours of
> time or days where they haven't entered time at all.
> If I select out of the table that holds the time I can get days where they
> haven't entered at least 8 hours (i.e. select emp_hours from emp_time where
> emp_hours < 8). But how do I also get days where time hasn't been entered
> since those days won't be in the table?
> Thanks,
> --
> Dan D.
|||Is there any other way? I'd rather not have to maintain another table.
Thanks,
Dan D.
"Tibor Karaszi" wrote:

> Create a calendar table and do an outer join against that table. Some info on calendar tables:
> http://www.aspfaq.com/show.asp?id=2519
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> Blog: http://solidqualitylearning.com/blogs/tibor/
>
> "Dan D." <DanD@.discussions.microsoft.com> wrote in message
> news:BED0D9F5-2515-4A14-B902-B2334EF59A57@.microsoft.com...
>
|||You can create that table on the fly, as a temp table. But I fail to see that problem of having such
table. You create it once and for all. If you hold 10 years, it is only about 3650 rows in it!
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Dan D." <DanD@.discussions.microsoft.com> wrote in message
news:BA3C552B-FA37-4657-B77A-1074C512E9AD@.microsoft.com...[vbcol=seagreen]
> Is there any other way? I'd rather not have to maintain another table.
> Thanks,
> --
> Dan D.
>
> "Tibor Karaszi" wrote:

query help

I have a name column that contains both first and last
names:
Col1
John Doe
I'd like to split it into two columns, a first and
lastname:
firstname lastname
-- --
John Doe
Anyone have any easy way to do this?
Do you *always* have two words, separated by a space? I.e., what does your data look like?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Rob" <anonymous@.discussions.microsoft.com> wrote in message news:c07e01c47a31$4e2ec290$a601280a@.phx.gbl...
> I have a name column that contains both first and last
> names:
> Col1
> --
> John Doe
> I'd like to split it into two columns, a first and
> lastname:
> firstname lastname
> -- --
> John Doe
> Anyone have any easy way to do this?
|||For the most part. There are some names that contain a
middle inital..
the data looks like this:
John Doe
Jane Doe
George W Bush
Bill Clinton
John Kerry
Jim Bob Smith
etc....
I'm not overly concerned with getting everything perfect.
To be honest, I'd be cool with just the first names.
>--Original Message--
>Do you *always* have two words, separated by a space?
I.e., what does your data look like?
>--
>Tibor Karaszi, SQL Server MVP
>http://www.karaszi.com/sqlserver/default.asp
>http://www.solidqualitylearning.com/
>
>"Rob" <anonymous@.discussions.microsoft.com> wrote in
message news:c07e01c47a31$4e2ec290$a601280a@.phx.gbl...
>
>.
>
|||This should get you started:
CREATE TABLE Presidents (
FullName varchar(50)
)
GO
INSERT INTO Frog VALUES ('George W Bush')
INSERT INTO Frog VALUES ('Bill Clinton')
INSERT INTO Frog VALUES ('Ronald Reagan')
INSERT INTO Frog VALUES ('George H Bush')
INSERT INTO Frog VALUES ('Gerald Ford')
INSERT INTO Frog VALUES ('Richard Nixon')
GO
SELECT LEFT(FullName, CHARINDEX(' ', FullName) -1) AS 'First Name',
CASE
WHEN PATINDEX('% _ %', FullName) > 0
THEN SUBSTRING(FullName, CHARINDEX(' ', FullName) +1, 1)
ELSE ''
END AS 'MI',
RIGHT(FullName, CHARINDEX(' ', REVERSE(FullName)) - 1) AS 'Last Name'
FROM Presidents
You can look up the various pieces used.
CHARINDEX
PATINDEX
SUBSTRING
REVERSE
CASE
Rick Sawtell
MCT, MCSD, MCDBA
|||Ummm. Change the INSERT INTO commands to reflect the Presidents table...
Sorry bout that.
Rick
"Rick Sawtell" <r_sawtell@.hotmail.com> wrote in message
news:%23FfBMvjeEHA.3792@.TK2MSFTNGP09.phx.gbl...
> This should get you started:
> CREATE TABLE Presidents (
> FullName varchar(50)
> )
> GO
> INSERT INTO Frog VALUES ('George W Bush')
> INSERT INTO Frog VALUES ('Bill Clinton')
> INSERT INTO Frog VALUES ('Ronald Reagan')
> INSERT INTO Frog VALUES ('George H Bush')
> INSERT INTO Frog VALUES ('Gerald Ford')
> INSERT INTO Frog VALUES ('Richard Nixon')
> GO
>
> SELECT LEFT(FullName, CHARINDEX(' ', FullName) -1) AS 'First Name',
> CASE
> WHEN PATINDEX('% _ %', FullName) > 0
> THEN SUBSTRING(FullName, CHARINDEX(' ', FullName) +1,
1)
> ELSE ''
> END AS 'MI',
> RIGHT(FullName, CHARINDEX(' ', REVERSE(FullName)) - 1) AS 'Last
Name'
> FROM Presidents
>
> You can look up the various pieces used.
> CHARINDEX
> PATINDEX
> SUBSTRING
> REVERSE
> CASE
> Rick Sawtell
> MCT, MCSD, MCDBA
>
|||Cool, that did it. One other thing though... Could the
same be used for an address column? I used the same
syntax, but ran into an issue...
The column has a street address:
123 N. Main St.
I used the SQL and pulled the house number, directional,
and suffix, but lost the street name. Any help?
Thanks!

>--Original Message--
>Ummm. Change the INSERT INTO commands to reflect the
Presidents table...[vbcol=seagreen]
>Sorry bout that.
>
>Rick
>
>"Rick Sawtell" <r_sawtell@.hotmail.com> wrote in message
>news:%23FfBMvjeEHA.3792@.TK2MSFTNGP09.phx.gbl...
AS 'First Name',[vbcol=seagreen]
(' ', FullName) +1,[vbcol=seagreen]
>1)
(FullName)) - 1) AS 'Last
>Name'
>
>.
>
|||Ummm..
Use the SUBSTRING function to get everything to the right of your
directional. Then apply the same CHARINDEX or PATINDEX functions to the
return value you are looking for from the return value of the SUBSTRING
function.
On a separate note... SQL really isn't the best choice to be doing
procedural language things like this.
If you dumped everything to a text file and used VBScript, you could
probably get this thing hashed out more quickly.
Rick
"Rob" <anonymous@.discussions.microsoft.com> wrote in message
news:c45a01c47a48$9c9aef50$a301280a@.phx.gbl...[vbcol=seagreen]
> Cool, that did it. One other thing though... Could the
> same be used for an address column? I used the same
> syntax, but ran into an issue...
> The column has a street address:
> 123 N. Main St.
> I used the SQL and pulled the house number, directional,
> and suffix, but lost the street name. Any help?
> Thanks!
> Presidents table...
> AS 'First Name',
> (' ', FullName) +1,
> (FullName)) - 1) AS 'Last

Query help

I need to update 6 column on 1 table depending on 2 other
columns on another table (All 8 columns exists on both
tables)
here is what I am trying to write and it gives me error:
Update Table1
Set start_date = (Select start_date from Table2),
end_date = (Select end_date from Table2),
user1 = (Select user1 from Table2),
user2 = (Select user2 from Table2),
user3 = (Select user3 from Table2),
user4 = (Select user4 from Table2)
FROM Table2
Where Table2.project = Table1.project AND
Table2.Pjt_entity = Table1.Pjt_entity
Thanks for any help.
Hi,
Try this,
Update Table1
Set a.start_date = b.start_date ,
a.end_date = b.end_date,
a.user1 = b.user1,
a.user2 = b.user2,
a.user3 = b.user3,
a.user4 = b.user4
FROM Table1 a,Table2 b
Where a.project = b.project
AND a..Pjt_entity = b.Pjt_entity
Tahnks
Hari
MCDBA
"Todd" <anonymous@.discussions.microsoft.com> wrote in message
news:2d2001c486d0$5a97bdb0$a301280a@.phx.gbl...
> I need to update 6 column on 1 table depending on 2 other
> columns on another table (All 8 columns exists on both
> tables)
> here is what I am trying to write and it gives me error:
> Update Table1
> Set start_date = (Select start_date from Table2),
> end_date = (Select end_date from Table2),
> user1 = (Select user1 from Table2),
> user2 = (Select user2 from Table2),
> user3 = (Select user3 from Table2),
> user4 = (Select user4 from Table2)
> FROM Table2
> Where Table2.project = Table1.project AND
> Table2.Pjt_entity = Table1.Pjt_entity
> Thanks for any help.
|||Todd wrote:
> I need to update 6 column on 1 table depending on 2 other
> columns on another table (All 8 columns exists on both
> tables)
> here is what I am trying to write and it gives me error:
> Update Table1
> Set start_date = (Select start_date from Table2),
> end_date = (Select end_date from Table2),
> user1 = (Select user1 from Table2),
> user2 = (Select user2 from Table2),
> user3 = (Select user3 from Table2),
> user4 = (Select user4 from Table2)
> FROM Table2
> Where Table2.project = Table1.project AND
> Table2.Pjt_entity = Table1.Pjt_entity
> Thanks for any help.
Well if you have a 1:1 between the tables, you just need to specify the
column to update:
Update Table1
Set start_date = b.start_date,
end_date = b.end_date,
etc...
FROM Table2 b
Where b.project = Table1.project AND
b.Pjt_entity = Table1.Pjt_entity
David G.
|||David G. wrote:
> Todd wrote:
> Well if you have a 1:1 between the tables, you just need to specify
> the column to update:
> Update Table1
> Set start_date = b.start_date,
> end_date = b.end_date,
> etc...
> FROM Table2 b
> Where b.project = Table1.project AND
> b.Pjt_entity = Table1.Pjt_entity
Left off a table in the FROM clause. See Hari's post instead.
David G.

Query Help

Hi All,
I'm not sure if this even possible.
Here is the query from NorthWind database:
SELECT TOP 3 Employees.EmployeeID,
Orders.CustomerID
FROM Orders,Employees
WHERE Employees.EmployeeID = 9
AND Orders.EmployeeID = Employees.EmployeeID
Result:
EmployeeID CustomerID
9 RICSU
9 ERNSH
9 SAVEA
Is there a way to return this query as 1 record and name columns
CustomerID1, CustomerID2, CustomerID3
EmployeeID CustomerID1 CustomerID2
CustomerID3
9 RICSU ERNSH
SAVEA
Thanks,
Walter
I'd say do that in your user interface code rather than in SQL. Leave
the database for what it does best - retrieving data. How difficult can
it be to display a data set as horizontal list?
Certainly you can do it in the database, but do you really want 3
*random* customers for each employee? You haven't specified ORDER BY in
your query so you can't predict which three customers you'll get back.
Let's assume that you really wanted the first three orders placed by an
employee:
SELECT MAX(employeeid),
MAX(CASE WHEN ord = 1 THEN customerid END),
MAX(CASE WHEN ord = 2 THEN customerid END),
MAX(CASE WHEN ord = 3 THEN customerid END)
FROM
(SELECT O1.employeeid, O1.customerid, COUNT(*) AS ord
FROM Orders AS O1
JOIN Orders AS O2
ON O1.employeeid = O2.employeeid
AND (O1.orderdate > O2.orderdate OR
(O1.orderdate = O2.orderdate AND O1.orderid >= O2.orderid))
WHERE O1.employeeid =9
GROUP BY O1.employeeid, O1.customerid, O1.orderdate
HAVING COUNT(*)<=3) AS T ;
David Portas
SQL Server MVP
|||David,
Thanks for your help.Works like a champ!
I don't have an interface for this query.
Walter
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1124208616.358495.95330@.g47g2000cwa.googlegro ups.com...
> I'd say do that in your user interface code rather than in SQL. Leave
> the database for what it does best - retrieving data. How difficult can
> it be to display a data set as horizontal list?
> Certainly you can do it in the database, but do you really want 3
> *random* customers for each employee? You haven't specified ORDER BY in
> your query so you can't predict which three customers you'll get back.
> Let's assume that you really wanted the first three orders placed by an
> employee:
> SELECT MAX(employeeid),
> MAX(CASE WHEN ord = 1 THEN customerid END),
> MAX(CASE WHEN ord = 2 THEN customerid END),
> MAX(CASE WHEN ord = 3 THEN customerid END)
> FROM
> (SELECT O1.employeeid, O1.customerid, COUNT(*) AS ord
> FROM Orders AS O1
> JOIN Orders AS O2
> ON O1.employeeid = O2.employeeid
> AND (O1.orderdate > O2.orderdate OR
> (O1.orderdate = O2.orderdate AND O1.orderid >= O2.orderid))
> WHERE O1.employeeid =9
> GROUP BY O1.employeeid, O1.customerid, O1.orderdate
> HAVING COUNT(*)<=3) AS T ;
> --
> David Portas
> SQL Server MVP
> --
>

Query Help

I have a table <ClearanceORDER>
The Fields of interest are <ClearDate> , <ClearanceType>, <ClearanceOrderID>
The Problem:
When an order is Canceled (CNCL) or Change of address (COA) there is an
entry in this table for it. The entry should look like this:
ClearDate ClearanceType ClearanceOrderID
09/14/2007 COA 212
canceled order
07/09/2007 CNCL 547
Change of address
A person can NOT be 'canceled' and 'change of address' in the same
clearanceorderid and the same cleardate!
IN an other way.
How can I list all the records that have COA and CNCL with the same
cleardate and clearanceorderid?
I dont know how else to explain this.
Scott BurkeScott,
To prevent this from happening in the future, you could add an unique
index/constraint on ClearDate and ClearanceOrderID, so there will be only
one entry per day and per OrderID, no matter what type that is.
To display what entries in the table break that rule, use this:
select ClearanceOrderID, ClearDate
from ClearanceOrder
group by ClearanceOrderID, ClearDate
having count(*) > 1
Andrei.
"Scott Burke" <ScottBurke@.discussions.microsoft.com> wrote in message
news:5497C818-B7C0-4A17-835E-2AA139899281@.microsoft.com...
>I have a table <ClearanceORDER>
> The Fields of interest are <ClearDate> , <ClearanceType>,
> <ClearanceOrderID>
> The Problem:
> When an order is Canceled (CNCL) or Change of address (COA) there is an
> entry in this table for it. The entry should look like this:
> ClearDate ClearanceType ClearanceOrderID
> 09/14/2007 COA 212
> canceled order
> 07/09/2007 CNCL 547
> Change of address
> A person can NOT be 'canceled' and 'change of address' in the same
> clearanceorderid and the same cleardate!
> IN an other way.
> How can I list all the records that have COA and CNCL with the same
> cleardate and clearanceorderid?
> I dont know how else to explain this.
> Scott Burke
>|||Thanks Andrei !
For some dam reason I thought I had to generate a list of COA and CNCL then
compare them.
Tunnal vission I guess. :)
Thanks again.
Just for giggles......
is is possibe to do the above?
Scott Burke
"Andrei" wrote:
> Scott,
> To prevent this from happening in the future, you could add an unique
> index/constraint on ClearDate and ClearanceOrderID, so there will be only
> one entry per day and per OrderID, no matter what type that is.
> To display what entries in the table break that rule, use this:
> select ClearanceOrderID, ClearDate
> from ClearanceOrder
> group by ClearanceOrderID, ClearDate
> having count(*) > 1
>
> Andrei.
> "Scott Burke" <ScottBurke@.discussions.microsoft.com> wrote in message
> news:5497C818-B7C0-4A17-835E-2AA139899281@.microsoft.com...
> >I have a table <ClearanceORDER>
> > The Fields of interest are <ClearDate> , <ClearanceType>,
> > <ClearanceOrderID>
> >
> > The Problem:
> > When an order is Canceled (CNCL) or Change of address (COA) there is an
> > entry in this table for it. The entry should look like this:
> > ClearDate ClearanceType ClearanceOrderID
> > 09/14/2007 COA 212
> > canceled order
> > 07/09/2007 CNCL 547
> > Change of address
> >
> > A person can NOT be 'canceled' and 'change of address' in the same
> > clearanceorderid and the same cleardate!
> >
> > IN an other way.
> > How can I list all the records that have COA and CNCL with the same
> > cleardate and clearanceorderid?
> >
> > I dont know how else to explain this.
> > Scott Burke
> >
>
>sql

query help

i need to include in my query a filter for dates. i need to just return
records that have happened in the last six months. I do i do this. help
please.
i have a startdate and a enddate field.try date between startdate and dateadd(m,-6,startdate)
"Nat Johnson" wrote:
> i need to include in my query a filter for dates. i need to just return
> records that have happened in the last six months. I do i do this. help
> please.
> i have a startdate and a enddate field.

Query Help

I have query with following column names:
cust_no, Firm_no, Name, homeaddress, homecity, homestate, homezip,
officeaddress, officecity, officestate, officezip
I want to be able to pull it this way that whenever there is a certain
unique Firm_no it should populate the homeaddress, homecity, homestate,
homezip for this customer.
What do I have to do to accomplish this?
ThanksU can achieve this by the following way:
Use the following expresson to display Homeaddress:
=IIF(IsNothing(Previous(Fields!Firm_no.Value)),
Fields!homeaddress.Value,
IIF(Fields!Firm_no.Value = Previous(Fields!Firm_no.Value),
"",
Fields!homeaddress.Value))
In the same way implement the same logic to display homecity, homestate,
homezip.
Regards,
SaraS|||saras,
I have a unique firm_no that I want to use when my report runs it should
look like:
Custo_no Firm_no Name Address City State Zip
123 1111 Jon Doe Main Dallas TX 75000
321 1122 Jon Doe Globe Pano TX 75001
So when anytime the Firm_no is '1122' I want the address to print their
homeaddress.
Thanks for your help.
"saras" wrote:
> U can achieve this by the following way:
> Use the following expresson to display Homeaddress:
> =IIF(IsNothing(Previous(Fields!Firm_no.Value)),
> Fields!homeaddress.Value,
> IIF(Fields!Firm_no.Value = Previous(Fields!Firm_no.Value),
> "",
> Fields!homeaddress.Value))
>
> In the same way implement the same logic to display homecity, homestate,
> homezip.
> Regards,
> SaraS
>|||Thanks Saras, It worked I just dint have it in the correct place. Stupid
typo mistake. Thanks a bunch have a great day!
"saras" wrote:
> U can achieve this by the following way:
> Use the following expresson to display Homeaddress:
> =IIF(IsNothing(Previous(Fields!Firm_no.Value)),
> Fields!homeaddress.Value,
> IIF(Fields!Firm_no.Value = Previous(Fields!Firm_no.Value),
> "",
> Fields!homeaddress.Value))
>
> In the same way implement the same logic to display homecity, homestate,
> homezip.
> Regards,
> SaraS
>|||Saras,
Sorry to bother again...but now its printing all the homeaddress I still
have this questions:
I have query with following column names:
cust_no, Firm_no, Name, homeaddress, homecity, homestate, homezip,
officeaddress, officecity, officestate, officezip
I want to be able to pull it this way that whenever there is a certain
unique Firm_no it should populate the homeaddress, homecity, homestate,
homezip for this customer.
What do I have to do to accomplish this?
Thanks
"Shan" wrote:
> I have query with following column names:
> cust_no, Firm_no, Name, homeaddress, homecity, homestate, homezip,
> officeaddress, officecity, officestate, officezip
> I want to be able to pull it this way that whenever there is a certain
> unique Firm_no it should populate the homeaddress, homecity, homestate,
> homezip for this customer.
> What do I have to do to accomplish this?
> Thanks|||Ok. I have these fields.
Cust_no, Firm_name, Firm_no, Name, OfficeAddr, OffCity, OffSt, OffZip,
HomeAddr, Homecity, HomeSt, HomeZip
In my report I only want to show based on my query the following format
Custo_no Firm_name Firm_no Name Address City State Zip
123 Keller 1111 Jon Doe Main Dallas TX 75000
321 Ebby 1122 Jon Doe Globe Pano TX 75009
102 Cold 1234 Jon Doe Holly Plano TX 75002
103 Nonmember 1000 Jon Doe Trench Allen TX 75001
109 Nonmember 1000 Jon Doe Trail Prosper TX 75003
Now I want to populate the Address field with customer's homeAddr anytime
the firm_no is 1000 which is a Non member otherwise if the firm_no is
anything else then populate the Address with their OfficeAddr. The Firm_no
1000 doesn't have an OfficeAddr so we want to populate it with customer's
homeaddr.
Thanks for your help.
"Shan" wrote:
> saras,
> I have a unique firm_no that I want to use when my report runs it should
> look like:
> Custo_no Firm_no Name Address City State Zip
> 123 1111 Jon Doe Main Dallas TX 75000
> 321 1122 Jon Doe Globe Pano TX 75001
> So when anytime the Firm_no is '1122' I want the address to print their
> homeaddress.
> Thanks for your help.
> "saras" wrote:
> > U can achieve this by the following way:
> >
> > Use the following expresson to display Homeaddress:
> >
> > =IIF(IsNothing(Previous(Fields!Firm_no.Value)),
> > Fields!homeaddress.Value,
> > IIF(Fields!Firm_no.Value = Previous(Fields!Firm_no.Value),
> > "",
> > Fields!homeaddress.Value))
> >
> >
> > In the same way implement the same logic to display homecity, homestate,
> > homezip.
> >
> > Regards,
> > SaraS
> >

query help

Here is a simplified example of what I need to accomplish.

I have a table that keeps track of plastic balls in tubs. Based on a bit column the record is either defining balls added to a tub or taken away. When the record is defined as adding balls to a tub it will say how many and what color, but when the flag says they have been taken away from a tub I only know the number removed and not the color.

There are multiple tubs and multiple colors. So say tub1 has 20 balls in it (50% red, %25 green, and %25 blue). Also say tub2 has 10 balls in it (100% red). This is our starting point.

Now on day one, 5 balls from tub two are put into tub one. So we know that 5 balls of 100% red are put into tub one. This means that tub one now has 25 balls in it. By doing some weighted percentages, tub one now has these percentages: red = 60%, green = 20%, and blue = 20%.

Say on day two however, 5 balls are removed from tub one and placed back into tub two. We cannot say anything about the colors, but that they are: .6red, .2green, and .2 blue. So if we want a percentage for tub two on day 2 we now get: .8red, .1green and .1blue.

The math for the new percentage is I believe = ((originalPercent * originalCount) + (addedPercent * addedAmount)) / newTotalBallCount

I need a query that will give me the percentages of the different colors in the tub for any given day. This is really a running percentage that has to take every transaction into account.

This is a complicated query fro me to figure out, but can someone point me in the right direction?

LLeuthard wrote:

Say on day two however, 5 balls are removed from tub one and placed back into tub two. We cannot say anything about the colors, but that they are: .6red, .2green, and .2 blue. So if we want a percentage for tub two on day 2 we now get: .8red, .1green and .1blue.

too superfluous.

is this thing about permutation and combination/? how did u say taht 6r,2g,2b?

|||Are you saying it is not worth my time or that it is impossible? Is there a stored proc I could write that would do this easily?|||

I got .6Red .2Blue and .2Green by saying that:

5 balls of 100% red were moved to tub1. so tub1 originally has a estimate of .5*20 = 10Red balls.

Take the estimate of 10Red and add the estimate of 5Red and we get an estimate of 15Red out of 25 in tub1. This makes for .6Red at the end of day 1.

Do the same with the others.

Query help

DECLARE @.Test TABLE (AccountNo INT, Invoicedate datetime, dex_row_id INT)

INSERT @.Test
SELECT 1180, '05/05/2006', 1 UNION ALL
SELECT 1180, '06/05/2006',2 UNION ALL
SELECT 1180, '04/05/2006',3 UNION ALL
SELECT 1180, '07/05/2006',4 UNION ALL
SELECT 1181, '09/05/2006',1 UNION ALL
SELECT 1181, '10/05/2006',2 UNION ALL
SELECT 1181, '05/05/2006',3 UNION ALL
SELECT 1182, '06/05/2006',1

-- I want a delete first month row for each accounts. If account has more then one row for same accountno and invoice date then i want a select any one and delete.
-- I wrote this but did not work because for min dex_row_id and min invoicedate combination.

--delete the firest month data for each accountno
DELETE FROM @.test WHERE LTRIM(RTRIM(CONVERT(VARCHAR,AccountNo)))+'@.'+CONVERT(VARCHAR,Invoicedate,101)+'@.'+CONVERT(VARCHAR,DEX_ROW_ID) IN
(SELECT LTRIM(RTRIM(CONVERT(VARCHAR,AccountNo)))+'@.'+CONVERT(VARCHAR,MIN(Invoicedate),101)+'@.'+CONVERT(VARCHAR,MIN(DEX_ROW_ID)) FROM @.test
GROUP BY AccountNo)

-- select statment
select * from @.test where
CONVERT(VARCHAR,AccountNo)+'@.'+CONVERT(VARCHAR,Invoicedate,101)+'@.'+CONVERT(VARCHAR,dex_row_id)in (
select CONVERT(VARCHAR,AccountNo)+'@.'+CONVERT(VARCHAR,min(Invoicedate),101)+'@.'+CONVERT(VARCHAR,min(dex_row_id))
from @.test group by AccountNo)

--selecting all record
select * from @.test

need helpDo you want to delete all except the last date in each account or only delete the earliest date in each account?|||

Dhaval:

I looked through what you requested. See if below is what you mean

Dave

DECLARE @.Test TABLE (AccountNo INT, Invoicedate datetime, dex_row_id INT)

INSERT @.Test
SELECT 1180, '05/05/2006', 1 UNION ALL
SELECT 1180, '06/05/2006',2 UNION ALL
SELECT 1180, '04/05/2006',3 UNION ALL
SELECT 1180, '07/05/2006',4 UNION ALL
SELECT 1180, '07/05/2006',5 UNION ALL
SELECT 1181, '09/05/2006',1 UNION ALL
SELECT 1181, '10/05/2006',2 UNION ALL
SELECT 1181, '05/05/2006',3 UNION ALL
SELECT 1182, '06/05/2006',1

-- I want a delete first month row for each accounts. If account has more then one row for same accountno and invoice date then i want a select any one and delete.
-- I wrote this but did not work because for min dex_row_id and min invoicedate combination.

/*
--delete the firest month data for each accountno
DELETE FROM @.test WHERE LTRIM(RTRIM(CONVERT(VARCHAR,AccountNo)))+'@.'+CONVERT(VARCHAR,Invoicedate,101)+'@.'+CONVERT(VARCHAR,DEX_ROW_ID) IN
(SELECT LTRIM(RTRIM(CONVERT(VARCHAR,AccountNo)))+'@.'+CONVERT(VARCHAR,MIN(Invoicedate),101)+'@.'+CONVERT(VARCHAR,MIN(DEX_ROW_ID)) FROM @.test
GROUP BY AccountNo)
*/

print '-- '
print '-- Records before deletions: -- '
print '--'
select * from @.test order by accountNo, invoiceDate

delete from @.test
from ( select accountNo,
min (invoiceDate) as min_invoiceDate
from @.test
group by accountNo
) x
inner join @.test a
on x.accountNo = a.accountNo
and x.min_invoiceDate = a.invoiceDate

delete from @.test
from (
select accountNo,
invoiceDate,
min (dex_row_id) min_dex_row_id,
count(*) as recCt
from @.test
group by accountNo,
invoiceDate
having count(*) > 1
) x
inner join @.test a
on x.accountNo = a.accountNo
and x.invoiceDate = a.invoiceDate
and x.min_dex_row_id <> a.dex_row_id

-- select statment
/*
select * from @.test where
CONVERT(VARCHAR,AccountNo)+'@.'+CONVERT(VARCHAR,Invoicedate,101)+'@.'+CONVERT(VARCHAR,dex_row_id)in (
select CONVERT(VARCHAR,AccountNo)+'@.'+CONVERT(VARCHAR,min(Invoicedate),101)+'@.'+CONVERT(VARCHAR,min(dex_row_id))
from @.test group by AccountNo)
*/

--selecting all record
print ' '
print ' '
print '-- '
print '-- Records after deletions: -- '
print '--'
select * from @.test

--need help

-- --
-- -- Records before deletions: --
-- --
-- AccountNo Invoicedate dex_row_id
-- -- -- --
-- 1180 2006-04-05 00:00:00.000 3
-- 1180 2006-05-05 00:00:00.000 1
-- 1180 2006-06-05 00:00:00.000 2
-- 1180 2006-07-05 00:00:00.000 4
-- 1180 2006-07-05 00:00:00.000 5
-- 1181 2006-05-05 00:00:00.000 3
-- 1181 2006-09-05 00:00:00.000 1
-- 1181 2006-10-05 00:00:00.000 2
-- 1182 2006-06-05 00:00:00.000 1


-- --
-- -- Records after deletions: --
-- --
-- AccountNo Invoicedate dex_row_id
-- -- -- --
-- 1180 2006-05-05 00:00:00.000 1
-- 1180 2006-06-05 00:00:00.000 2
-- 1180 2006-07-05 00:00:00.000 4
-- 1181 2006-09-05 00:00:00.000 1
-- 1181 2006-10-05 00:00:00.000 2

Query Help

I have this scenario. What will be my query?

Table:

Account#, Name, RMR, Billing_Date, Invoice#

1000,Dave,50, 5/1/2006,10

1000,Dave,50, 6/1/2006,11

1000,Dave,50, 7/1/2006,12

1000,Dave,50, 8/1/2006,13

1000,Dave,50, 9/1/2006,14

2000,Al,50, 5/15/2006,15

2000,Al,50, 6/15/2006,16

2000,Al,50, 7/15/2006,17

2000,Al,50, 8/15/2006,18

3000,Jim,50, 8/10/2006,19

3000,Jim,50, 9/10/2006,20

3000,Jim,50, 10/10/2006,21

I use this query to calculate revenue sharing.

Account hit for revenue sharing after we bill the 4th billing month. In this case for Account# 1000 qualified after 8/1/2006, 2000 – 8/15/2006 and 3000 will be qualified after 11/10/2006. Each month we will pay 4% of RMR for all qualified accounts.

I want a query result with return for each month and find out how many accounts are qualified for each month.

In this case:

Septmeber-2006 -1000

Septmeber-2006 -2000

Octomber-2006 -1000

Could you define your result again based on the sample data you posted, which will help to understand your question. Thanks.|||

Dhaval:

I was able to mock-up what you described below. Is this more-or-less what you are looking for?

Dave


declare @.rmrMockUp table
( Account# integer not null,
Name varchar (20) not null,
RMR numeric (9,2) not null,
Billing_Date datetime not null,
Invoice# integer not null
)

insert into @.rmrMockUp values ( 1000, 'Dave', 50, '5/1/2006', 10 )
insert into @.rmrMockUp values ( 1000, 'Dave', 50, '6/1/2006', 11 )
insert into @.rmrMockUp values ( 1000, 'Dave', 50, '7/1/2006', 12 )
insert into @.rmrMockUp values ( 1000, 'Dave', 50, '8/1/2006', 13 )
insert into @.rmrMockUp values ( 1000, 'Dave', 50, '9/1/2006', 14 )
insert into @.rmrMockUp values ( 2000, 'Al', 50, '5/15/2006', 15 )
insert into @.rmrMockUp values ( 2000, 'Al', 50, '6/15/2006', 16 )
insert into @.rmrMockUp values ( 2000, 'Al', 50, '7/15/2006', 17 )
insert into @.rmrMockUp values ( 2000, 'Al', 50, '8/15/2006', 18 )
insert into @.rmrMockUp values ( 3000, 'Jim', 50, '8/10/2006', 19 )
insert into @.rmrMockUp values ( 3000, 'Jim', 50, '9/10/2006', 20 )
insert into @.rmrMockUp values ( 3000, 'Jim', 50, '10/10/2006', 21 )

declare @.monthList varchar (250)
set @.monthList = 'January February March April May June July August September October November December '

select Account#,
rtrim (substring (@.monthList,
month (dateadd (month, 1, Billing_date))*10-9, 10)) + '-' +
convert (char (4), year (dateadd (month, 1, Billing_date)))
as RMR_Month
from
( select Account#,
rmr,
Rank() over (partition by Account# order by Billing_Date)
as activeMonths,
Billing_Date
from @.rmrMockUp
) x
where activeMonths >= 4
order by Billing_Date, Account#

-- -
-- Query Output:
-- -

-- Account# RMR_Month
-- --
-- 1000 September-2006
-- 2000 September-2006
-- 1000 October-2006

Query help

I need help with this query.

My query is a lot more complicated than this but I have distilled it down to this in an example. Since this query will involve many tables and many rows I need it to be as efficient as possible.

My query is retrieving "car", each of these "car"s can have N "features", each "feature" can have 1 "car". I need to get a COUNT on the "features".

Here is what my query looks like so far:

SELECT Car_ID, Car_Name, Manufacturer_ID
FROM [Car], [Manufacturer]
WHERE Car_ManID = Manufacturer_ID

I need to add in something like this:

SELECT Car_ID, Car_Name, Manufacturer_ID, Count(Features) as FeatureCount
FROM [Cars], [Manufacturer], [Feature]
WHERE Car_ManID = Manufacturer_ID AND Feature_CarID = CarID AND CarID = '4'

Now, I know this won't work but you get the point.

Basically, I want to have results like this

Car_ID Car_Name Manufactuere_ID FeatureCount
12 Escort Ford 12
34 Tahoe Chevy 0

Then query must account for feature counts of zero, so I assume some sort of outer join will be needed?add a group by


SELECT Car_ID, Car_Name, Manufacturer_ID, Count(Features) as FeatureCount
FROM [Cars], [Manufacturer], [Feature]
WHERE Car_ManID = Manufacturer_ID AND Feature_CarID = CarID AND CarID = '4'
group by Car_ID, Car_Name, Manufacturer_ID

hth|||Thanks for the reply, I actually just found out about MS SQL derived tables. That works perfect!

query help

I have a table with multiple records for an identical person. It is a rolling history of the applications a user has submitted. How can I grab the most current application by the date most closest to todays date. Obviously one of my fields is an applied date.
I need help in creating a query.select * from table t where datefield = (select max(datefield) from table where userid = t.userid)

Nick

Query help

My table are

Customer: customerId ,name

Order: orderId, customerId, product,date

I want to display all of the customer which have order or not. I want display name, product,date . If the customer do not order I want display only customer name.For example:

Name Product Date

John Video 09/20/2007

Mary -- ----

How can I write sql or sp?

I suggest you do some reading on SQL and joins in particular as this is something that you should learn so you can write these queries yourself.

DECLARE @.CUSTOMERTABLE (customeridint IDENTITY(1,1),name varchar(20))DECLARE @.ORDERSTABLE (orderidint IDENTITY(1,1), customeridint, productvarchar(20), orderdatedatetime)INSERT @.CUSTOMERVALUES ('Fred')INSERT @.CUSTOMERVALUES ('Joe')INSERT @.ORDERSVALUES (1,'Video',GetDate())SELECT c.name, o.product, o.orderdateFROM @.CUSTOMER cLEFTOUTER JOIN @.ORDERS oON o.customerid = c.customerid
|||

use left join instead of inner join

select cust.customerId ,cust.name,ord.orderId, ord.customerId, ord.product,ord.date from Customer cust left outer join orders ord on

cust.CustomerId = ord.CusomerId

|||

Hi,

I think you have to create a cross-tab query, it's ilttle tricky but interesting.

Check these following links

http://www.databasejournal.com/features/mssql/article.php/3521101

http://www.oreillynet.com/pub/a/network/2004/12/17/crosstab.html

or you can adopt the following solution

http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1131829,00.html

Regards,

Sandeep

|||

ASP.NET Dev:

I think you have to create a cross-tab query,

That's not necessary as they aren't pivoting any data (or at least that doesn't appear to be the case based on their description).

|||

Ozo:

How can I write sql or sp?

you can write sql as..

select customer.name, order.product, order.orderdate from customer left outer join order on customer.customerid = order.customerid

and sp as..

CREATE PROCEDURE [dbo].[usp_CustomerOrder]
AS
BEGIN
SET NOCOUNT ON
select customer.name, order.product, order.orderdate from customer leftouter join order on customer.customerid = order.customerid
END

|||

Tahnk you for your helping.

|||

Ozo:

Tahnk you for your helping.

You should also mark all the posts that helped by using the "Mark As Answer" link so that future readers with the same problem will know which methods to use.

|||

I have a new question I want to display the latest order from the customer .Can you help me?

|||

Yes, but please start a new question if you have something else to ask as it helps keep the forum tidy and easier to search.

Query help

Hello Everyone,

Please can you help me with this?

I have an audit table, so there are many id's and modified dates... I am looking to get the last updated record for each ID. This is what I have so far... "which still gives duplicate ID's"

I have see many pages about distincta and max/min... I cannot make sense of it... HELP

1Select *2FROM TabelA3WhereExists (SELECT distinct max (id)as id ,max (ModifiedDate)as ModifiedDate4FROM TabelA)5Order by id
I tried to break it down, and still I get duplicate ID's
1Select *2FROM TabelA3Where idIN (SELECT distinct id4FROM TabelA)5Order by id

Try

SELECT *FROM TableAWHERECONVERT (nvarchar,max(ModifiedDate),126 ) +' '+ IDEXISTS IN (selectCONVERT (nvarchar,max(ModifiedDate),126 ) +' '+ IDas [key]from TableAgroup by ID)ORDER BY ID
|||

Thanks for your reply,

I get the following error

Msg 156, Level 15, State 1, Line 3

Incorrect syntax near the keyword 'EXISTS'.

|||

SQL Server 2005:

SELECT id, ModifiedDateFROM(SELECT id, ModifiedDate, row_number()OVER(partitionby idorderby ModifiedDateDESC)as RowNum

FROM TableA) t

WHERE t.RowNum=1

For SQL Server 2000, you can try:

SELECT id, ModifiedDateFROM(SELECT id, ModifiedDate,(SELECTcount(*)FROM TABLEA aWHERE a.id=a1.idand a1.ModifiedDate<=a.ModifiedDate)as RowNum

FROM TableA a1) t

WHERE t.RowNum=1

|||

That's why your anAll-Star!....Shot for the help... it works very well.

Thanks B

sql

Query Help

Hi All,

I want to display the data in vertical format though the data is stored horizontally in the datatable.Suppose i have table with five columns-id.a,b,c,d.If i use a select statement that will give me the data in the format-ID A B C D

but now i want to display the data as

ID A

ID B

ID C

ID D

Any help on this pls??I m thinking to use the self join but would it take a long time??

Thanks

select id,a

union

select id,b

union

select id,c

union

select id,d

|||It sounds to me more like you require a pivot query rather than a union. If you have Sql Server 2005 you can do pivot queries but, unfortunately, not in the older versions. There a good article you can readhere that explains how to do pivot queries.|||

You can do pivot tables in Sql Server 2000. Just search for "pivot tables" in the Books Online. The example there was greatly helpful to me with the same issue.

Hope this helps

query help

i have a table that stores employee records. I then have a history employee table that stores changes to each particular employee (one to many ). Everytime a changes is made to an employee I record their old record in a history table. I want to be able to query against the history table and pull up the "last entry". How would I write a query for this, I am recording a timestamp.You haven't shared any DDL, so I'm guessing on keys and column names. But you should get the idea from this...
SELECT *
FROM EmployeeHistory eh
WHERE eh.theDate =
(SELECT MAX(eh2.theDate)
FROM EmployeeHistory eh2
WHERE eh2.EmployeeId = eh.EmployeeId)

|||

You might want to match on a identity field instead. It will be more reliable then a date field. The date field could always have multiple records with the same date.
Nick

|||Depends on the business rules. If there are multiple rows thatwere updated at exactly the same time, which one is most recent? Or should both be displayed?

Query Help

I have a query that returns a recordset that contains this kind of data:

Description Rate Amount

item1 2 .32

item2 3 1.34

item3 5 12.33

I want change the query to put all this data in ONE single field. What is the best why to do this?


Thanks!


What the result will look like in the ONE single field?

|||

item1 2 .32 item2 3 1.34 item3 5 12.33

Just all these dumped into one field like above. However id like to use the final query in and update so i cant simply concatenate each field then each row and save it in a variable.

I have the query below but i cant use it in an update for multiple records without using a fetch, or at least I cant figure out a better way.


DECLARE @.blob varchar(2000)

SELECT
@.blob = ISNULL(@.blob,'') + (def.[description] + ' ' +
CAST(sd.amount as varchar(10)) + ' ' +
CAST(sd.minutes as varchar(10)) + CHAR(13) + CHAR(10) )
FROM
section_detail sd,
def_section_detail_description def
WHERE
sd.def_section_detail_descr_id = def.def_section_detail_descr_id
and sd.section_id = 2274893453

Query help

I have a project almost (or so I thought!) completed but now I need to add a column to a table which is throwing everything off. Right now I have TableMain which queries TableA. I need to add a column (bit) to TableMain and then run a query that is basicallyif (bitColumn) query TableB, else query TableA.for each row.

TableA contains a listing, TableB is groups where each group contains multiple items from TableA. The columns I want to pull from each table have the same names (ie. regardless of bitColumn, I want TableA.Name or TableB.Name)

I'm not sure how I can go about doing this, I greatly appreciate any help.

Can you please give following details.

Primary key and Fkey in each table

Example input and output data

|||

Paper (id(pkey), name, code, description, clipID(fkey), etc) <= Think of these as a sheet of paper.

Clip(id(pkey), name, description) <= Think of these as a group of papers paperclipped together.

Cart(id(pkey),user,paperID(fkey),qty)

if someone tries to order a paper that has a clipID, they are forced to buy the entire paperclip. My shopping cart works for regular papers, and I have it notifying the user that they are really ordering the paperclip. What I'm stuck on is displaying the shopping cart, etc.

Shopping Cart: Paper1 + Paper2 + Clip1, where Clip1 has Paper3 and Paper4.

I don't know how to make the cart show Clip1 or whether I should just force add each individual item to the shopping cart (making editing qtys difficult), etc. I was thinking about adding an isClip column to the cart and then the stored procudure returns Paper.name or Clip.name depending on whether isClip is 0 or 1... so that it would be

Cart(id(pkey),user,paperID(fkey),qty,isClip)

I don't know how I would write that query, and I'm not sure its even the best designSad [:(]

|||

I would design like this.

Category table

Products Table

Product details table

In category table : categories are paper and clip

In products table: Different papers(only papers not associated with clips) and clips

In product Details table: Papers that goes with clips

Papers that are associated to clips are only sold as a bunch

When user click on paper, show paper details and when user clicks on clip, show all the papers associated to clip by querying from product details table.

|||A better design would be to have ALL papers clipped, even if it is only clipping a single paper. Then the user can only buy clips.|||

With all of the code already written, I'd like to avoid a complete design restructuring.

Motley: this is what I started working on last night until I ran into a problem. Each paper belongs to a certain topic, and in the catalog are listed under topic headings as the sp returns with order by topic. The papers in a clip do not need to (and rarely will) belong to the same topic. I could have a Clips topic that I display first and then the individual topics, but it would involve checking each clip and seeing how many papers reference it; or perhaps adding a Count field to the Clips table? I would still then need to figure out a way to return the correct ordering...I'm open to hearing other suggestions...

|||

edit...yeah, that doesn't work, never mind...

SELECT

clip.id, clip.name, clip.description,

ISNULL(paper.topic,'CLIP')

FROM

clips clip

LEFT JOIN

papers paper

ON

clip.id = paper.kitID

ORDER BY

topic

|||

Basic query:

SELECT c.id as ClipID,c.Name as ClipName,c.Description as ClipDescription,p.id as PaperID,p.name as PaperName, p.code as PaperCode, p.Description as PaperDescription, etc

FROM clip c

JOIN paper p ON (c.PaperID=p.id)

Return clips and how many papers are attached:

SELECT c.id AS ClipID,c.name,c.description,COUNT(*)

FROM clip c

JOIN paper p ON (c.PaperID=p.id)

GROUP BY c.id,c.name,c.description

Of course this assumes that each paper has a clip associated with it.

With your original structure:

SELECT s.*,name,description

FROM cart s

JOIN clip c ON (s.ID=c.id and s.isClip=1)

UNION

SELECT s.*,name,description

FROM cart s

JOIN paper p ON (s.ID=p.id and s.isClip=0)

OR

SELECT s.*,CASE WHEN c.id IS NOT NULL THEN c.name ELSE p.name END as Name, CASE WHEN c.id IS NOT NULL THEN c.description ELSE p.description END as Description

FROM cart s

LEFT JOIN clip c ON (c.id=s.id and s.isClip=1)

LEFT JOIN paper p ON (p.id=s.id and s.isClip=0)

sql

Query Help

SQL DB Query Help
I have several suppliers of products.
When a customer does a Search
I want to return only the Lowest cost items by Part Number.
The query could return many different Part Numbers.
I also need to return Description, Part Number, Qty on Hand, Supplier etc.
These are all in the table.
Note that Description, Qty and Supplier are usually different.
Example items in DB
Part Desc Cost Qty Supplier
123 Widget 1.00 10 1
123 A Widget 2.00 5 2
123 Widget A 3.00 20 3
567 B Widget 9.00 3 1
567 Widget B 8.00 17 2
567 Widget 12.00 8 3

I would like to return
Part Desc Cost Qty Supplier
123 Widget 1.00 10 1
567 Widget B 8.00 17 2

Thanks in advance

Perhaps something like this:

SELECT
P.* FROM Parts P
INNER JOIN
(
SELECT P3.part as PartNum, MIN(P3.Cost) as MinCost
FROM Parts P3
GROUP BY P3.Part) AS P2
ON P.Part = P2.partnum
AND P.cost = P2.mincost

Query help

Hi,
I have a single row in a table:

Title Desc Quantity
----------
aaaa bbbbb 4

and I need the query to insert "Qty" number of records into a second table, e.g

Title1 Desc1
------
aaaa bbbbb
aaaa bbbbb
aaaa bbbbb
aaaa bbbbb

I reckon its some sort of self join but any help would be appreciated.

gregFor the example below I use a function, but you can also use any table that contains sequencial numbers with no gaps. A table with IDENTITY field that did not have any deletes would do.

set nocount on
create table t1 (
title char(4) not null,
[desc] varchar(50) not null,
quantity int not null)
go
create table t2 (
title1 char(4) not null,
desc1 varchar(50) not null)
go
insert t1 values ('aaaa', 'bbbbb', 4)
insert t1 values ('bbbb', 'ccccc', 1)
insert t1 values ('cccc', 'ddddd', 3)
insert t1 values ('dddd', 'eeeee', 2)
insert t1 values ('eeee', 'fffff', 5)
go
insert t2
select title, [desc] from dbo.fn_CartesianProduct() f
inner join t1 on f.[id] < t1.quantity order by 1
go
drop table t1, t2
go|||Excellent - I have an Integers table that substitutes nicely.
Thanks.

Query Help

Hello,

I am not sure whether is possible to do that with query.

I have this table

User Flag
A X1
A X2
A X3
B X1
B X5
C X7

and I need to get this table

User All_Flags
A X1 X2 X3
B X1 X5
C X7

Thank you for help
DJThis has been very popular lately

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=40520|||I'd use:CREATE TABLE Drahos (
[User] CHAR(1)
, Flag CHAR(2)
)

INSERT INTO Drahos (
[user], Flag
) SELECT 'A', 'X1' UNION ALL SELECT 'A', 'X2'
UNION ALL SELECT 'A', 'X3' UNION ALL SELECT 'B', 'X1'
UNION ALL SELECT 'B', 'X5' UNION ALL SELECT 'C', 'X7'
GO
CREATE FUNCTION dbo.fDrahos(
@.pcUser CHAR(1)
) RETURNS VARCHAR(255) AS BEGIN

DECLARE @.cFlags VARCHAR(255)

SELECT @.cFlags = Coalesce(@.cFlags + ',', '') + Flag
FROM Drahos
WHERE [User] = @.pcUser

RETURN @.cFlags
END
GO

SELECT DISTINCT [User], dbo.fDrahos([User]) AS All_Flags
FROM Drahos-PatP|||Maybe it's a new question on a certification test ;-)

Query Help

I have two tables: Trans & History. For each record in Trans, there can be
many in History. I want to return records in the Trans table that have a
certain status in the History table but not other statuses. Here's an
example:
select transactions.transaction_id,
name
from transactions
inner join statusHistory SH1 on
transactions.transaction_id = SH1.transaction_id
where eMonth = '10' and eYear = '2005' and
SH1.status in ('Rec', 'R1Rec') and
SH1.status not in ('Coll', 'RTR')
The returned records contain both the status of 'Rec' and 'Coll/'RTR' but I
want to filter out those that contain either 'Coll' or 'RTR'On Wed, 23 Nov 2005 10:36:02 -0800, Eric wrote:

>I have two tables: Trans & History. For each record in Trans, there can b
e
>many in History. I want to return records in the Trans table that have a
>certain status in the History table but not other statuses. Here's an
>example:
>select transactions.transaction_id,
> name
>from transactions
>inner join statusHistory SH1 on
> transactions.transaction_id = SH1.transaction_id
>where eMonth = '10' and eYear = '2005' and
> SH1.status in ('Rec', 'R1Rec') and
> SH1.status not in ('Coll', 'RTR')
>
>The returned records contain both the status of 'Rec' and 'Coll/'RTR' but I
>want to filter out those that contain either 'Coll' or 'RTR'
Hi Eric,
Since you didn't post your table structure (CREATE TABLE statements),
sample data (INSERT statements) and required output, I'll have to do
some wild guess about which of your unprefixed columns belog to which
table. You'll probably have to make some changes. But here's a general
outline:
SELECT T.transaction_id, T.name
FROM transactions AS T
WHERE T.eMonth = '10'
AND T.eYear = '2005'
AND EXISTS
(SELECT *
FROM statusHistory AS SH1
WHERE SH1.transaction_id = T.transaction_id
AND SH1.status IN ('Rec', 'R1Rec'))
AND NOT EXISTS
(SELECT *
FROM statusHistory AS SH2
WHERE SH2.transaction_id = T.transaction_id
AND SH2.status IN ('Col1', 'RTR'))
BTW, why store a date in seperate columns eMonth and eYear? Isn't that
what the datetime datatype is for?
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hi There,
Use LEFT JOIN instead of Join
With Warm regards
Jatinder Singh

Query Help

Hi,
I have two tables
Products
--
ProductId
ProductTitle
Bids
--
BidId
ProductId
BidAmount
BidderName
I want to grab all the products with the highest bidAmount and the BidderNam
e.
There could be multiple bidders for each product.Try:
select
p.ProductID
, p.ProductTitle
, b.BidID
, b.BidAmount
, b.BidderName
from
Products p
join
Bidders b on b b.ProductID = p.ProductID
where
b.BidAmount =
(
select
max (b2.BidAmount)
from
Bidders b2
where
b2.ProductID = p.ProductID
)
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com
"dotnettester" <dotnettester@.discussions.microsoft.com> wrote in message
news:D60ADC91-6F30-49EE-A50C-63E3CAF9649A@.microsoft.com...
> Hi,
> I have two tables
> Products
> --
> ProductId
> ProductTitle
> Bids
> --
> BidId
> ProductId
> BidAmount
> BidderName
> I want to grab all the products with the highest bidAmount and the
> BidderName.
> There could be multiple bidders for each product.
>sql

Query Help

I'm trying to find the number of Mondays since 6/1/2005. Any suggestions?
THanks"Arul" <Arul@.discussions.microsoft.com> wrote in message
news:199031D2-BCCC-43EE-91F5-D5A20E47068C@.microsoft.com...
> I'm trying to find the number of Mondays since 6/1/2005. Any suggestions?
> THanks
http://www.aspfaq.com/show.asp?id=2519|||Try try the following:
declare @.dtcount datetime
declare @.days table
(
[Date] datetime
, [Day] int
)
set @.dtcount = '06/01/2005'
while @.dtcount <= getdate()
begin
if datepart(dw,@.dtcount) = 2
begin
insert into @.days
values (@.dtcount, datepart(dw,@.dtcount))
end
set @.dtcount = @.dtcount+1
end
select * from @.days
"Arul" wrote:

> I'm trying to find the number of Mondays since 6/1/2005. Any suggestions?
> THanks|||Arul wrote:
> I'm trying to find the number of Mondays since 6/1/2005. Any
> suggestions?
> THanks
Try this:
declare @.start datetime, @.today datetime, @.mondays int
set @.start='20050601'
set @.today= getdate()
set @.mondays= datediff(ww,@.start,@.today)
if datepart(dw,@.start)<3 set @.mondays=@.mondays+1
if datepart(dw,@.today) = 1 set @.mondays=@.mondays-1
select @.mondays
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.