Friday, March 30, 2012

query question

I saw a query in which there was a expression
SELECT
case when credit_flag&1 = 1 then 1 else 0 end as credit_default_flag1,
case when credit_flag&2 = 2 then 1 else 0 end as credit_default_flag2,
case when credit_flag&4 = 4 then 1 else 0 end as credit_default_flag3
FROM ...
What happens when we do column & 1, column & 2
THanks
Sanjay& is the bit-wise AND operator in T-SQL. So credit_flag &
1 will return 1 on the first bit only when the first bit
from the right (of credit_flag) is set to 1. And
credit_flag & 4 will return 1 on the third bit (thus
decimal 4) only when the third bit from the right (of
credit_flag) is set to 1.
Linchi
>--Original Message--
>I saw a query in which there was a expression
>SELECT
>case when credit_flag&1 = 1 then 1 else 0 end as
credit_default_flag1,
>case when credit_flag&2 = 2 then 1 else 0 end as
credit_default_flag2,
>case when credit_flag&4 = 4 then 1 else 0 end as
credit_default_flag3
>FROM ...
>
>What happens when we do column & 1, column & 2
>THanks
>Sanjay
>.
>|||HI Linch
Do you have some white paper or document which would explain more about these bit-wise operation
I think you explained what the result would be but i am not clear how bit-wise operations work at first plac
Thanks|||The bit-wise AND operator (also OR and XOR) is supported
in most, if not all, programming languages. You can pick
up any programming tutorial book and find information on
the bit-wise operations. You can also find the info in the
SQL Server Books Online.
Linchi
>--Original Message--
>HI Linchi
>Do you have some white paper or document which would
explain more about these bit-wise operations
>I think you explained what the result would be but i am
not clear how bit-wise operations work at first place
>Thanks
>.
>

Query question

Hi,
I am trying to use two databases in one query... and here is the simple
query I have created but it it throwing an error:
Server: Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near '@.db1'.
Declare @.db1 varchar(40)
Declare @.db2 varchar(40)
set @.db1 = 'PUBS'
set @.db2 = 'NORTHWIND'
USE @.db1
USE @.db2
SELECT * from authors
SELECT * from customers
What is that I am doing wrong... I went through SQL manual but no
help..
HJThe line number is wrong...
Server: Msg 170, Level 15, State 1, Line 5
Line 5: Incorrect syntax near '@.db1'.|||Oh by the way I am a complete novice to SQL and SQL server 2000 so
please exuse my stupid question...|||You can't have a variable for the USE command, quite simply.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Hitesh Joshi" <hitesh287@.gmail.com> wrote in message
news:1147809433.886525.234400@.i39g2000cwa.googlegroups.com...
> Hi,
> I am trying to use two databases in one query... and here is the simple
> query I have created but it it throwing an error:
> Server: Msg 170, Level 15, State 1, Line 7
> Line 7: Incorrect syntax near '@.db1'.
> Declare @.db1 varchar(40)
> Declare @.db2 varchar(40)
> set @.db1 = 'PUBS'
> set @.db2 = 'NORTHWIND'
> USE @.db1
> USE @.db2
> SELECT * from authors
> SELECT * from customers
> What is that I am doing wrong... I went through SQL manual but no
> help..
> HJ
>|||got ya.. so how about something like this...
Declare @.db1 varchar(40)
Declare @.db2 varchar(40)
set @.db1 = 'PUBS'
set @.db2 = 'NORTHWIND'
USE PUBS
USE NORTHWIND
SELECT * from @.db1.dbo.authors
SELECT * from @.db2.dbo.customers|||Same problem. You cannot have a variable as the database qualifier in a SELECT statement.
Perhaps you can explain what you want to achieve in the end, and you might get some suggestions...
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Hitesh Joshi" <hitesh287@.gmail.com> wrote in message
news:1147810701.999538.273200@.38g2000cwa.googlegroups.com...
> got ya.. so how about something like this...
> Declare @.db1 varchar(40)
> Declare @.db2 varchar(40)
> set @.db1 = 'PUBS'
> set @.db2 = 'NORTHWIND'
> USE PUBS
> USE NORTHWIND
> SELECT * from @.db1.dbo.authors
> SELECT * from @.db2.dbo.customers
>|||Here is what I want to do... I want to use two different tables from
two different databases on the same server. I could always write full
names of the tables and databases in my script but as I am a novice, I
thought there must be someway to put table_names and db_names in a
variable...
After doing some research and copy & paste... I came with something
like this...
Declare @.db1 varchar(40)
Declare @.db2 varchar(40)
Declare @.tbl_name1 varchar (40)
Declare @.tbl_name2 varchar (40)
select @.db1 = 'PUBS'
select @.db2 = 'NORTHWIND'
select @.tbl_name1 = 'authors'
select @.tbl_name2 = 'customers'
/*USE PUBS
USE NORTHWIND */
EXEC ('SELECT * from ' + @.db1 + '..' + @.tbl_name1)
EXEC ('SELECT * from ' + @.db2 + '..' + @.tbl_name2)
That worked but still do not understand that EXEC () thingy...
anyother way to accomplish this?
Thank you
HJ|||On 16 May 2006 13:37:04 -0700, Hitesh Joshi wrote:
(snip)
>EXEC ('SELECT * from ' + @.db1 + '..' + @.tbl_name1)
>EXEC ('SELECT * from ' + @.db2 + '..' + @.tbl_name2)
>That worked but still do not understand that EXEC () thingy...
>anyother way to accomplish this?
Hi HJ,
http://www.sommarskog.se/dynamic_sql.html
--
Hugo Kornelis, SQL Server MVPsql

Query question

Hi I have a large stored procedure that performs several queries
conditionally on a database depending on values that are passed into the
procedure. Anyhow I am using a string search and have set up
SELECT @.stringvar='%' + @.stringvar + '%'
then have
case when @.stringvar IS NOT NULL then
'AND (table.field LIKE @.stringvar)'
ELSE ''
It works fine just could not remember why I needed to have the
SELECT @.stringvar='%' + @.stringvar + '%' statement.
thanks,
--
Paul G
Software engineer.The CASE statement is there to include or exclude that condition in the
query; however, it is a lousy implementation. You are obviously using
dynamic sql inside of a stored procedure. Other than a convenient place to
put it, dyanmical sql inside a proc reduces the effectiveness of using
stored procedure.
The '%' before and after the passed in parameter are wildcard characters
that allow any string as a substitute. So, any string plus parameter plus
any string becomes the search condition. You are gauranteed to do a table
scan or clustered index scan as that criteria could never be supported by an
index.
As a better solution, try something more like this:
SELECT Col1, Col2, ..., Coln
FROM Tab1 JOIN Tab2
ON Tab1.Key1 = Tab2.Key1
AND Tab1.Key1 = Tab2.Key2
...
AND Tab1.Keyn = Tab2.Keyn
...
...
JOIN Tabn
ON ...
WHERE criterion1 AND criterion2 ... AND criterionN
AND (@.stringvar IS NULL
OR TabX.ColX LIKE (@.stringvar + '%')
)
This is executed directly. There is no need for a variable nor the use of
the EXEC(@.var) function. TabX.ColX can be indexed and used if it is highly
selectable. The query execution plan can be reused.
Hope this helps.
Sincerely,
Anthony Thomas
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:B39C178F-3ABF-4EB2-99F1-3BEA896DC966@.microsoft.com...
Hi I have a large stored procedure that performs several queries
conditionally on a database depending on values that are passed into the
procedure. Anyhow I am using a string search and have set up
SELECT @.stringvar='%' + @.stringvar + '%'
then have
case when @.stringvar IS NOT NULL then
'AND (table.field LIKE @.stringvar)'
ELSE ''
It works fine just could not remember why I needed to have the
SELECT @.stringvar='%' + @.stringvar + '%' statement.
thanks,
--
Paul G
Software engineer.|||Hi thanks for the response. It did seem like there would be a better way
other than the dynamic sql. Someone had suggested to me from this newsgroup
to use it so I went that route. No official SQL training so just learning by
trail and error.
"AnthonyThomas" wrote:
> The CASE statement is there to include or exclude that condition in the
> query; however, it is a lousy implementation. You are obviously using
> dynamic sql inside of a stored procedure. Other than a convenient place to
> put it, dyanmical sql inside a proc reduces the effectiveness of using
> stored procedure.
> The '%' before and after the passed in parameter are wildcard characters
> that allow any string as a substitute. So, any string plus parameter plus
> any string becomes the search condition. You are gauranteed to do a table
> scan or clustered index scan as that criteria could never be supported by an
> index.
> As a better solution, try something more like this:
> SELECT Col1, Col2, ..., Coln
> FROM Tab1 JOIN Tab2
> ON Tab1.Key1 = Tab2.Key1
> AND Tab1.Key1 = Tab2.Key2
> ...
> AND Tab1.Keyn = Tab2.Keyn
> ...
> ...
> JOIN Tabn
> ON ...
> WHERE criterion1 AND criterion2 ... AND criterionN
> AND (@.stringvar IS NULL
> OR TabX.ColX LIKE (@.stringvar + '%')
> )
> This is executed directly. There is no need for a variable nor the use of
> the EXEC(@.var) function. TabX.ColX can be indexed and used if it is highly
> selectable. The query execution plan can be reused.
> Hope this helps.
> Sincerely,
>
> Anthony Thomas
>
> --
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:B39C178F-3ABF-4EB2-99F1-3BEA896DC966@.microsoft.com...
> Hi I have a large stored procedure that performs several queries
> conditionally on a database depending on values that are passed into the
> procedure. Anyhow I am using a string search and have set up
> SELECT @.stringvar='%' + @.stringvar + '%'
> then have
> case when @.stringvar IS NOT NULL then
> 'AND (table.field LIKE @.stringvar)'
> ELSE ''
> It works fine just could not remember why I needed to have the
> SELECT @.stringvar='%' + @.stringvar + '%' statement.
> thanks,
> --
> Paul G
> Software engineer.
>
>

query question

I have shopping cart and the items are stored in a
StoreCart table. I'm trying to write a query that
returns the items in the cart in certain way but I don't
know how to do it. Say for example that I have the
following items:
Product Qty
-- --
Toy_1 3
Toy_2 1
Toy_3 2
I want to write a query that will return the item the
number of times that the Qty field has.
Product
--
Toy_1
Toy_1
Toy_1
Toy_2
Toy_3
Toy_3
How can I do this?
TIA,
Vic"Vic" <vduran@.specpro-inc.com> wrote in message
news:0e4201c53fcc$350cb270$a501280a@.phx.gbl...
>I have shopping cart and the items are stored in a
> StoreCart table. I'm trying to write a query that
> returns the items in the cart in certain way but I don't
> know how to do it. Say for example that I have the
> following items:
> Product Qty
> -- --
> Toy_1 3
> Toy_2 1
> Toy_3 2
> I want to write a query that will return the item the
> number of times that the Qty field has.
> Product
> --
> Toy_1
> Toy_1
> Toy_1
> Toy_2
> Toy_3
> Toy_3
>
create table N(i int primary key)
go
set nocount on
declare @.i int
set @.i = 0
while @.i < 10000
begin
insert into N(i) values (@.i)
set @.i = @.i + 1
end
go
create table cart(product varchar(50) not null, Qty int not null, primary
key (Product,qty))
insert into cart(product,qty)values('Toy_1',3)
insert into cart(product,qty)values('Toy_2',1)
insert into cart(product,qty)values('Toy_3',2)
go
select product
from
cart
join N on n.i < cart.qty
order by product
David

query question

Hi I have 3 tables and am wondering if there is a way to do this. I would
like a qerry that returns data for a data item but will return only the # of
records for the event and not the destination. For example if the query
returns data for Data ID 4
I would want to see as the results.
Data name event destination
report recieved office
report intransit frontdesk
Even though there are 3 destinations I would like to only list the first 2
and base the number of records returned on the number of events. Thanks.
table1 event
******************************************
*pri key Count * foriegn key Data ID * event *
* 1 * 3 * arrived *
* 2 * 4 * recieved *
* 3 * 4 * intransit *
******************************************
table2 data item
*****************************
* Pri key Data ID * Data name *
* 3 * email *
* 4 * report *
*****************************
table3- destination-note no prim key
**********************************
* Data ID * destination *
* 4 * office *
* 4 * frontdesk *
* 4 * mailroom *
**********************************
--
Paul G
Software engineer.Hi Paul
See http://www.aspfaq.com/etiquette.asp?id=5006 on how to post useful DDL
and example data in a usable format, also posting the expected output from
the data provided would be helpful e.g.
CREATE TABLE [event] ( [Count] int, [Data ID] int, [event] varchar(30) )
INSERT INTO [event] ( [Count], [Data ID], [event] )
SELECT 1, 3, 'arrived'
UNION ALL SELECT 2, 4, 'recieved'
UNION ALL SELECT 3, 4, 'intransit'
CREATE TABLE [data item] ( [Data ID] int, [Data name] varchar(30) )
INSERT INTO [data item] ( [Data ID], [Data name] )
SELECT 3, 'email'
UNION ALL SELECT 4, 'report'
CREATE TABLE destination ( [Data ID] int, destination varchar(30) )
INSERT INTO destination ( [Data ID], destination )
SELECT 4, 'office'
UNION ALL SELECT 4, 'frontdesk'
UNION ALL SELECT 4, 'mailroom'
There is no way to easily distinguish your destinations e.g
SELECT d.[Data name], e.[Event], f.destination
FROM [Data Item] d
JOIN [Event] e ON d.[Data Id] = e.[Data Id]
JOIN destination f ON f.[Data Id] = e.[Data Id]
ORDER BY e.[Count] DESC
Returns
Data name Event destination
-- -- --
report intransit office
report intransit frontdesk
report intransit mailroom
report recieved office
report recieved mailroom
report recieved frontdesk
(6 row(s) affected)
Limiting this to top 2
SELECT TOP 2 d.[Data name], e.[Event], f.destination
FROM [Data Item] d
JOIN [Event] e ON d.[Data Id] = e.[Data Id]
JOIN destination f ON f.[Data Id] = e.[Data Id]
ORDER BY e.[Count] DESC
Returns
Data name Event destination
-- -- --
report intransit office
report intransit frontdesk
(2 row(s) affected)
You could give destination alphabetical rank such as
SELECT f.[Data ID], f.destination,
( SELECT COUNT(*) FROM destination b WHERE f..destination <
b.destination )+1 AS RANK
FROM destination f
This may then allow you to pick different destinations by joining to the
event count (you may have to rank these to get similar number ranges.
SELECT TOP 2 d.[Data name], e.[Event], g.destination
FROM [Data Item] d
JOIN [Event] e ON d.[Data Id] = e.[Data Id]
JOIN ( SELECT f.[Data ID],
f.destination,
( SELECT COUNT(*) FROM destination b WHERE f.destination < b.destination )+1
AS RANK
FROM destination f
) g ON g.[Data Id] = e.[Data Id] AND e.[count] = g.rank
ORDER BY e.[Count] DESC
Data name Event destination
-- -- --
report intransit frontdesk
report recieved mailroom
(2 row(s) affected)
John
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:7FC06E5C-8E29-4F97-9268-F7E9A6878C03@.microsoft.com...
> Hi I have 3 tables and am wondering if there is a way to do this. I would
> like a qerry that returns data for a data item but will return only the #
> of
> records for the event and not the destination. For example if the query
> returns data for Data ID 4
> I would want to see as the results.
> Data name event destination
> report recieved office
> report intransit frontdesk
> Even though there are 3 destinations I would like to only list the first 2
> and base the number of records returned on the number of events. Thanks.
> table1 event
> ******************************************
> *pri key Count * foriegn key Data ID * event *
> * 1 * 3 * arrived
> *
> * 2 * 4 * recieved
> *
> * 3 * 4 * intransit
> *
> ******************************************
> table2 data item
> *****************************
> * Pri key Data ID * Data name *
> * 3 * email *
> * 4 * report *
> *****************************
> table3- destination-note no prim key
> **********************************
> * Data ID * destination *
> * 4 * office *
> * 4 * frontdesk *
> * 4 * mailroom *
> **********************************
>
> --
> Paul G
> Software engineer.|||hi thanks for the response. Does seem quite useful to use DDL, will do this
in the future. Unfortunately I will net be able to use a constant for the #
of records returned as the number of records returned for each data item will
not be the destinations but the number of events for each data item. Guess I
will probably use 2 queries the first one getting the # of events for each
data item and the second returning the data name, event and destination and
using the TOP or ROWCOUNT to limit the # of records returned. Thanks again,
Paul.
--
Paul G
Software engineer.
"John Bell" wrote:
> Hi Paul
> See http://www.aspfaq.com/etiquette.asp?id=5006 on how to post useful DDL
> and example data in a usable format, also posting the expected output from
> the data provided would be helpful e.g.
> CREATE TABLE [event] ( [Count] int, [Data ID] int, [event] varchar(30) )
> INSERT INTO [event] ( [Count], [Data ID], [event] )
> SELECT 1, 3, 'arrived'
> UNION ALL SELECT 2, 4, 'recieved'
> UNION ALL SELECT 3, 4, 'intransit'
> CREATE TABLE [data item] ( [Data ID] int, [Data name] varchar(30) )
> INSERT INTO [data item] ( [Data ID], [Data name] )
> SELECT 3, 'email'
> UNION ALL SELECT 4, 'report'
>
> CREATE TABLE destination ( [Data ID] int, destination varchar(30) )
> INSERT INTO destination ( [Data ID], destination )
> SELECT 4, 'office'
> UNION ALL SELECT 4, 'frontdesk'
> UNION ALL SELECT 4, 'mailroom'
>
> There is no way to easily distinguish your destinations e.g
> SELECT d.[Data name], e.[Event], f.destination
> FROM [Data Item] d
> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> JOIN destination f ON f.[Data Id] = e.[Data Id]
> ORDER BY e.[Count] DESC
> Returns
> Data name Event destination
> -- -- --
> report intransit office
> report intransit frontdesk
> report intransit mailroom
> report recieved office
> report recieved mailroom
> report recieved frontdesk
> (6 row(s) affected)
>
> Limiting this to top 2
> SELECT TOP 2 d.[Data name], e.[Event], f.destination
> FROM [Data Item] d
> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> JOIN destination f ON f.[Data Id] = e.[Data Id]
> ORDER BY e.[Count] DESC
> Returns
> Data name Event destination
> -- -- --
> report intransit office
> report intransit frontdesk
> (2 row(s) affected)
> You could give destination alphabetical rank such as
>
> SELECT f.[Data ID], f.destination,
> ( SELECT COUNT(*) FROM destination b WHERE f..destination <
> b.destination )+1 AS RANK
> FROM destination f
> This may then allow you to pick different destinations by joining to the
> event count (you may have to rank these to get similar number ranges.
> SELECT TOP 2 d.[Data name], e.[Event], g.destination
> FROM [Data Item] d
> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> JOIN ( SELECT f.[Data ID],
> f.destination,
> ( SELECT COUNT(*) FROM destination b WHERE f.destination < b.destination )+1
> AS RANK
> FROM destination f
> ) g ON g.[Data Id] = e.[Data Id] AND e.[count] = g.rank
> ORDER BY e.[Count] DESC
> Data name Event destination
> -- -- --
> report intransit frontdesk
> report recieved mailroom
> (2 row(s) affected)
> John
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:7FC06E5C-8E29-4F97-9268-F7E9A6878C03@.microsoft.com...
> > Hi I have 3 tables and am wondering if there is a way to do this. I would
> > like a qerry that returns data for a data item but will return only the #
> > of
> > records for the event and not the destination. For example if the query
> > returns data for Data ID 4
> > I would want to see as the results.
> > Data name event destination
> > report recieved office
> > report intransit frontdesk
> >
> > Even though there are 3 destinations I would like to only list the first 2
> > and base the number of records returned on the number of events. Thanks.
> >
> > table1 event
> > ******************************************
> > *pri key Count * foriegn key Data ID * event *
> > * 1 * 3 * arrived
> > *
> >
> > * 2 * 4 * recieved
> > *
> >
> > * 3 * 4 * intransit
> > *
> >
> > ******************************************
> > table2 data item
> > *****************************
> > * Pri key Data ID * Data name *
> > * 3 * email *
> >
> > * 4 * report *
> >
> > *****************************
> > table3- destination-note no prim key
> > **********************************
> > * Data ID * destination *
> > * 4 * office *
> >
> > * 4 * frontdesk *
> > * 4 * mailroom *
> >
> > **********************************
> >
> >
> >
> > --
> > Paul G
> > Software engineer.
>
>|||Hi
SQL 2005 allows top to take a variable, but that may not be any use to
yourself. You may be able to use a having clause if you can formulate the
number of rows required and then use the ranking as the tested value.
John
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:0881ACE2-979C-425A-B53B-3627D46A6A05@.microsoft.com...
> hi thanks for the response. Does seem quite useful to use DDL, will do
> this
> in the future. Unfortunately I will net be able to use a constant for the
> #
> of records returned as the number of records returned for each data item
> will
> not be the destinations but the number of events for each data item.
> Guess I
> will probably use 2 queries the first one getting the # of events for each
> data item and the second returning the data name, event and destination
> and
> using the TOP or ROWCOUNT to limit the # of records returned. Thanks
> again,
> Paul.
> --
> Paul G
> Software engineer.
>
> "John Bell" wrote:
>> Hi Paul
>> See http://www.aspfaq.com/etiquette.asp?id=5006 on how to post useful DDL
>> and example data in a usable format, also posting the expected output
>> from
>> the data provided would be helpful e.g.
>> CREATE TABLE [event] ( [Count] int, [Data ID] int, [event] varchar(30) )
>> INSERT INTO [event] ( [Count], [Data ID], [event] )
>> SELECT 1, 3, 'arrived'
>> UNION ALL SELECT 2, 4, 'recieved'
>> UNION ALL SELECT 3, 4, 'intransit'
>> CREATE TABLE [data item] ( [Data ID] int, [Data name] varchar(30) )
>> INSERT INTO [data item] ( [Data ID], [Data name] )
>> SELECT 3, 'email'
>> UNION ALL SELECT 4, 'report'
>>
>> CREATE TABLE destination ( [Data ID] int, destination varchar(30) )
>> INSERT INTO destination ( [Data ID], destination )
>> SELECT 4, 'office'
>> UNION ALL SELECT 4, 'frontdesk'
>> UNION ALL SELECT 4, 'mailroom'
>>
>> There is no way to easily distinguish your destinations e.g
>> SELECT d.[Data name], e.[Event], f.destination
>> FROM [Data Item] d
>> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
>> JOIN destination f ON f.[Data Id] = e.[Data Id]
>> ORDER BY e.[Count] DESC
>> Returns
>> Data name Event destination
>> -- -- --
>> report intransit office
>> report intransit frontdesk
>> report intransit mailroom
>> report recieved office
>> report recieved mailroom
>> report recieved frontdesk
>> (6 row(s) affected)
>>
>> Limiting this to top 2
>> SELECT TOP 2 d.[Data name], e.[Event], f.destination
>> FROM [Data Item] d
>> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
>> JOIN destination f ON f.[Data Id] = e.[Data Id]
>> ORDER BY e.[Count] DESC
>> Returns
>> Data name Event destination
>> -- -- --
>> report intransit office
>> report intransit frontdesk
>> (2 row(s) affected)
>> You could give destination alphabetical rank such as
>>
>> SELECT f.[Data ID], f.destination,
>> ( SELECT COUNT(*) FROM destination b WHERE f..destination <
>> b.destination )+1 AS RANK
>> FROM destination f
>> This may then allow you to pick different destinations by joining to the
>> event count (you may have to rank these to get similar number ranges.
>> SELECT TOP 2 d.[Data name], e.[Event], g.destination
>> FROM [Data Item] d
>> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
>> JOIN ( SELECT f.[Data ID],
>> f.destination,
>> ( SELECT COUNT(*) FROM destination b WHERE f.destination <
>> b.destination )+1
>> AS RANK
>> FROM destination f
>> ) g ON g.[Data Id] = e.[Data Id] AND e.[count] = g.rank
>> ORDER BY e.[Count] DESC
>> Data name Event destination
>> -- -- --
>> report intransit frontdesk
>> report recieved mailroom
>> (2 row(s) affected)
>> John
>> "Paul" <Paul@.discussions.microsoft.com> wrote in message
>> news:7FC06E5C-8E29-4F97-9268-F7E9A6878C03@.microsoft.com...
>> > Hi I have 3 tables and am wondering if there is a way to do this. I
>> > would
>> > like a qerry that returns data for a data item but will return only the
>> > #
>> > of
>> > records for the event and not the destination. For example if the
>> > query
>> > returns data for Data ID 4
>> > I would want to see as the results.
>> > Data name event destination
>> > report recieved office
>> > report intransit frontdesk
>> >
>> > Even though there are 3 destinations I would like to only list the
>> > first 2
>> > and base the number of records returned on the number of events.
>> > Thanks.
>> >
>> > table1 event
>> > ******************************************
>> > *pri key Count * foriegn key Data ID * event *
>> > * 1 * 3 * arrived
>> > *
>> >
>> > * 2 * 4 * recieved
>> > *
>> >
>> > * 3 * 4 * intransit
>> > *
>> >
>> > ******************************************
>> > table2 data item
>> > *****************************
>> > * Pri key Data ID * Data name *
>> > * 3 * email *
>> >
>> > * 4 * report *
>> >
>> > *****************************
>> > table3- destination-note no prim key
>> > **********************************
>> > * Data ID * destination *
>> > * 4 * office *
>> >
>> > * 4 * frontdesk *
>> > * 4 * mailroom *
>> >
>> > **********************************
>> >
>> >
>> >
>> > --
>> > Paul G
>> > Software engineer.
>>|||ok thanks for the additional information. I guess I could use the ROWCOUNT
which does take a variable. Hopefully we will upgrade to SQL 2005 but it
will be awhile.
--
Paul G
Software engineer.
"John Bell" wrote:
> Hi
> SQL 2005 allows top to take a variable, but that may not be any use to
> yourself. You may be able to use a having clause if you can formulate the
> number of rows required and then use the ranking as the tested value.
> John
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:0881ACE2-979C-425A-B53B-3627D46A6A05@.microsoft.com...
> > hi thanks for the response. Does seem quite useful to use DDL, will do
> > this
> > in the future. Unfortunately I will net be able to use a constant for the
> > #
> > of records returned as the number of records returned for each data item
> > will
> > not be the destinations but the number of events for each data item.
> > Guess I
> > will probably use 2 queries the first one getting the # of events for each
> > data item and the second returning the data name, event and destination
> > and
> > using the TOP or ROWCOUNT to limit the # of records returned. Thanks
> > again,
> > Paul.
> > --
> > Paul G
> > Software engineer.
> >
> >
> > "John Bell" wrote:
> >
> >> Hi Paul
> >>
> >> See http://www.aspfaq.com/etiquette.asp?id=5006 on how to post useful DDL
> >> and example data in a usable format, also posting the expected output
> >> from
> >> the data provided would be helpful e.g.
> >> CREATE TABLE [event] ( [Count] int, [Data ID] int, [event] varchar(30) )
> >>
> >> INSERT INTO [event] ( [Count], [Data ID], [event] )
> >>
> >> SELECT 1, 3, 'arrived'
> >>
> >> UNION ALL SELECT 2, 4, 'recieved'
> >>
> >> UNION ALL SELECT 3, 4, 'intransit'
> >>
> >> CREATE TABLE [data item] ( [Data ID] int, [Data name] varchar(30) )
> >>
> >> INSERT INTO [data item] ( [Data ID], [Data name] )
> >>
> >> SELECT 3, 'email'
> >>
> >> UNION ALL SELECT 4, 'report'
> >>
> >>
> >> CREATE TABLE destination ( [Data ID] int, destination varchar(30) )
> >>
> >> INSERT INTO destination ( [Data ID], destination )
> >>
> >> SELECT 4, 'office'
> >>
> >> UNION ALL SELECT 4, 'frontdesk'
> >>
> >> UNION ALL SELECT 4, 'mailroom'
> >>
> >>
> >> There is no way to easily distinguish your destinations e.g
> >>
> >> SELECT d.[Data name], e.[Event], f.destination
> >>
> >> FROM [Data Item] d
> >>
> >> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> >>
> >> JOIN destination f ON f.[Data Id] = e.[Data Id]
> >>
> >> ORDER BY e.[Count] DESC
> >>
> >> Returns
> >>
> >> Data name Event destination
> >>
> >> -- -- --
> >>
> >> report intransit office
> >>
> >> report intransit frontdesk
> >>
> >> report intransit mailroom
> >>
> >> report recieved office
> >>
> >> report recieved mailroom
> >>
> >> report recieved frontdesk
> >>
> >> (6 row(s) affected)
> >>
> >>
> >>
> >> Limiting this to top 2
> >>
> >> SELECT TOP 2 d.[Data name], e.[Event], f.destination
> >>
> >> FROM [Data Item] d
> >>
> >> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> >>
> >> JOIN destination f ON f.[Data Id] = e.[Data Id]
> >>
> >> ORDER BY e.[Count] DESC
> >>
> >> Returns
> >>
> >> Data name Event destination
> >>
> >> -- -- --
> >>
> >> report intransit office
> >>
> >> report intransit frontdesk
> >>
> >> (2 row(s) affected)
> >>
> >> You could give destination alphabetical rank such as
> >>
> >>
> >>
> >> SELECT f.[Data ID], f.destination,
> >>
> >> ( SELECT COUNT(*) FROM destination b WHERE f..destination <
> >> b.destination )+1 AS RANK
> >>
> >> FROM destination f
> >>
> >> This may then allow you to pick different destinations by joining to the
> >> event count (you may have to rank these to get similar number ranges.
> >>
> >> SELECT TOP 2 d.[Data name], e.[Event], g.destination
> >>
> >> FROM [Data Item] d
> >>
> >> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> >>
> >> JOIN ( SELECT f.[Data ID],
> >>
> >> f.destination,
> >>
> >> ( SELECT COUNT(*) FROM destination b WHERE f.destination <
> >> b.destination )+1
> >> AS RANK
> >>
> >> FROM destination f
> >>
> >> ) g ON g.[Data Id] = e.[Data Id] AND e.[count] = g.rank
> >>
> >> ORDER BY e.[Count] DESC
> >>
> >> Data name Event destination
> >>
> >> -- -- --
> >>
> >> report intransit frontdesk
> >>
> >> report recieved mailroom
> >>
> >> (2 row(s) affected)
> >>
> >> John
> >>
> >> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> >> news:7FC06E5C-8E29-4F97-9268-F7E9A6878C03@.microsoft.com...
> >> > Hi I have 3 tables and am wondering if there is a way to do this. I
> >> > would
> >> > like a qerry that returns data for a data item but will return only the
> >> > #
> >> > of
> >> > records for the event and not the destination. For example if the
> >> > query
> >> > returns data for Data ID 4
> >> > I would want to see as the results.
> >> > Data name event destination
> >> > report recieved office
> >> > report intransit frontdesk
> >> >
> >> > Even though there are 3 destinations I would like to only list the
> >> > first 2
> >> > and base the number of records returned on the number of events.
> >> > Thanks.
> >> >
> >> > table1 event
> >> > ******************************************
> >> > *pri key Count * foriegn key Data ID * event *
> >> > * 1 * 3 * arrived
> >> > *
> >> >
> >> > * 2 * 4 * recieved
> >> > *
> >> >
> >> > * 3 * 4 * intransit
> >> > *
> >> >
> >> > ******************************************
> >> > table2 data item
> >> > *****************************
> >> > * Pri key Data ID * Data name *
> >> > * 3 * email *
> >> >
> >> > * 4 * report *
> >> >
> >> > *****************************
> >> > table3- destination-note no prim key
> >> > **********************************
> >> > * Data ID * destination *
> >> > * 4 * office *
> >> >
> >> > * 4 * frontdesk *
> >> > * 4 * mailroom *
> >> >
> >> > **********************************
> >> >
> >> >
> >> >
> >> > --
> >> > Paul G
> >> > Software engineer.
> >>
> >>
> >>
>
>

Query question

Hi,
I am logging process data every 5 min, every record has a datetime field in
addition to the process data one of the requierements of the application is
to avg the data every 3 hours. is there any simple way to accomplish this
with a query or will it be better create a job that runs every 3 hrs and
average the last 3 hrs and insert the results into a new table.
ThanksJulio
If you need to agregate the data every three hours , so yes , create a job
"Julio Delgado" <jdelgado89@.hotmail.com> wrote in message
news:OWLI7ip4GHA.3400@.TK2MSFTNGP04.phx.gbl...
> Hi,
> I am logging process data every 5 min, every record has a datetime field
> in addition to the process data one of the requierements of the
> application is to avg the data every 3 hours. is there any simple way to
> accomplish this with a query or will it be better create a job that runs
> every 3 hrs and average the last 3 hrs and insert the results into a new
> table.
> Thanks
>

Query Question

I have a question that I will illustrate with the script below. As you can
see there two tables, airlines and routes. Each airline has a customer_rank
that indicates the preferred airline of the customer ie 1 is most preferred.
Each route has a name, cost and duration.
What I would like to do is write a query that returns one row for each route
with the columns : airline, cost and duration. I would like the airline
column to be based on the preferred carrier, irrespective of the cost and
duration.
Can someone please stop my head spinning?
Thanks, Tad
CREATE TABLE [dbo].[Airlines] (
[Airline] [char] (10) PRIMARY KEY,
[Customer_Rank] [tinyint] NOT NULL
)
CREATE TABLE [dbo].[Routes] (
[ID] [int] IDENTITY (1, 1) PRIMARY KEY,
[Airline] [char] (10) NOT NULL REFERENCES Airlines(Airline),
[Route] [char] (10) NOT NULL ,
[Cost] [numeric](18, 0) NOT NULL ,
[Duration] [numeric](18, 0) NOT NULL
)
INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
VALUES('BOAC',3)
INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
VALUES('TWA',2)
INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
VALUES('United',1)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
VALUES('BOAC', 'A2B', 150, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
VALUES('TWA', 'A2C', 200, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
VALUES('BOAC', 'B2C', 200, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
VALUES('United', 'A2B', 200, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
VALUES('United', 'D2E', 300, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
VALUES('BOAC', 'B2D', 300, 3)first of all you want to know which airline is the preferred carrier
for each route, so you have to inner join the two tables and find the
airline with the lowest (if highest substitute min by max) rank:
select route, min(customer_rank) rank
from routes r, airlines a
where a.airline=r.airline
group by route
with this query you get the the ranking of the preferred airline per
route. This output has to be inner joined with the airlines and routes
to get the desired result
select *
from airlines a,
routes r,
(
select route, min(customer_rank) rank
from routes r, airlines a
where a.airline=r.airline
group by route
) p
where a.customer_rank = p.rank
and r.route = p.route
and a.airline = r.airline
if you want to avoid an inner table (the stuff between (...)p) you
could create a view, but you will learn that in your next class.|||Hi
Thanks for the DDL and Example data, showing your expected results would
also be nice. You can either use a subquery in the where clause or a derived
table such as
SELECT A.[Customer_Rank],
R.[ID], R.[Airline], R.[Route], R.[Cost], R.[Duration]
FROM [dbo].[Routes] R
JOIN [dbo].[Airlines] A ON A.[Airline] = R.[Airline]
JOIN ( SELECT MIN(E.[Customer_Rank]) AS [Customer_Rank], D.[Route]
FROM [dbo].[Routes] D
JOIN [dbo].[Airlines] E ON D.[Airline] = E.[Airline]
GROUP BY D.[Route] ) F ON F.[Customer_Rank] = A.[Customer_Rank] AND
F.[Route] = R.[Route]
ORDER BY R.[Route], A.[Customer_Rank]
John
"Tadwick" wrote:
> I have a question that I will illustrate with the script below. As you can
> see there two tables, airlines and routes. Each airline has a customer_rank
> that indicates the preferred airline of the customer ie 1 is most preferred.
> Each route has a name, cost and duration.
> What I would like to do is write a query that returns one row for each route
> with the columns : airline, cost and duration. I would like the airline
> column to be based on the preferred carrier, irrespective of the cost and
> duration.
> Can someone please stop my head spinning?
> Thanks, Tad
>
> CREATE TABLE [dbo].[Airlines] (
> [Airline] [char] (10) PRIMARY KEY,
> [Customer_Rank] [tinyint] NOT NULL
> )
> CREATE TABLE [dbo].[Routes] (
> [ID] [int] IDENTITY (1, 1) PRIMARY KEY,
> [Airline] [char] (10) NOT NULL REFERENCES Airlines(Airline),
> [Route] [char] (10) NOT NULL ,
> [Cost] [numeric](18, 0) NOT NULL ,
> [Duration] [numeric](18, 0) NOT NULL
> )
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('BOAC',3)
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('TWA',2)
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('United',1)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('BOAC', 'A2B', 150, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('TWA', 'A2C', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('BOAC', 'B2C', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('United', 'A2B', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('United', 'D2E', 300, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('BOAC', 'B2D', 300, 3)|||Nite4Hawks and John,
You are both awesome. I am amazed to get responses with two different
techniques in such a short time. Are there pros and cons of the correlated
subquery vs derived table methods?
Thanks again, Tad
"Tadwick" wrote:
> I have a question that I will illustrate with the script below. As you can
> see there two tables, airlines and routes. Each airline has a customer_rank
> that indicates the preferred airline of the customer ie 1 is most preferred.
> Each route has a name, cost and duration.
> What I would like to do is write a query that returns one row for each route
> with the columns : airline, cost and duration. I would like the airline
> column to be based on the preferred carrier, irrespective of the cost and
> duration.
> Can someone please stop my head spinning?
> Thanks, Tad
>
> CREATE TABLE [dbo].[Airlines] (
> [Airline] [char] (10) PRIMARY KEY,
> [Customer_Rank] [tinyint] NOT NULL
> )
> CREATE TABLE [dbo].[Routes] (
> [ID] [int] IDENTITY (1, 1) PRIMARY KEY,
> [Airline] [char] (10) NOT NULL REFERENCES Airlines(Airline),
> [Route] [char] (10) NOT NULL ,
> [Cost] [numeric](18, 0) NOT NULL ,
> [Duration] [numeric](18, 0) NOT NULL
> )
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('BOAC',3)
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('TWA',2)
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('United',1)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('BOAC', 'A2B', 150, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('TWA', 'A2C', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('BOAC', 'B2C', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('United', 'A2B', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('United', 'D2E', 300, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Duration])
> VALUES('BOAC', 'B2D', 300, 3)sql

Query Question

How can I get similar results from a query like this >
SELECT au_lname, state
FROM authors
WHERE state IN ('CA', 'IN', 'MD')
Except to replace ('CA', 'IN', 'MD') With a field that will have a similar
format'
The Field is Misc it's contents are (100, 101, 102) and so on. I need to
display a row for each occurrence of 3 digits in that field and replacing
('CA', 'IN', 'MD') with something like (SELECT au_id FROM titleauthor
WHERE royaltyper < 50) is not the same thing..
I'm thinking I need some type of variable length array, but I am out of
practice and not sure, can some one please help me.."WANNABE" <breichenbach AT istate DOT com> wrote in message
news:e34iWyJwGHA.1216@.TK2MSFTNGP03.phx.gbl...
> How can I get similar results from a query like this >
> SELECT au_lname, state
> FROM authors
> WHERE state IN ('CA', 'IN', 'MD')
> Except to replace ('CA', 'IN', 'MD') With a field that will have a similar
> format'
> The Field is Misc it's contents are (100, 101, 102) and so on. I need to
> display a row for each occurrence of 3 digits in that field and replacing
> ('CA', 'IN', 'MD') with something like (SELECT au_id FROM titleauthor
> WHERE royaltyper < 50) is not the same thing..
> I'm thinking I need some type of variable length array, but I am out of
> practice and not sure, can some one please help me..
>
I'm not completely following here, but you can use either an IN clause or a
WHERE EXISTS clause.
Perhaps something like:
SELECT au_id
FROM titleauthor
WHERE SomeValue IN (SELECT myLookupValues FROM sometable WHERE
somecondition)
Rick Sawtell
MCT, MCSD, MCDBA|||Thanks for you response Rick, but I think what you have described below is
what I have been trying to get to work. When I run this >>
SELECT au_lname, state
FROM authors
WHERE state IN ('CA', 'IN', 'MD')
I get a long list of records. I would like to get the same long list of
records by running something like the following query, AFTER I HAVE MODIFIED
THE stores TABLE TO INCLUDE THE stid FIELD and ENTERED THE VALUE (CA, IN,
MD) into that field for the record where stor_id is equal to 7067.
When I run this next query AFTER I have made the modifications described
above, I get only column headers>>
SELECT au_lname, state
FROM authors
WHERE state IN
(SELECT stid
FROM stores
WHERE stor_id = '7067')
This is all done in testing using the PUBS database, and here are the
queries used to modify that db
alter table pubs.dbo.stores add stid char(50)
UPDATE stores
SET [stid] = '(CA, IN, MD)'
where stor_id = '7067'
======================================="Rick Sawtell" <Quickening@.msn.com> wrote in message
news:%23OwzMOKwGHA.1288@.TK2MSFTNGP02.phx.gbl...
> "WANNABE" <breichenbach AT istate DOT com> wrote in message
> news:e34iWyJwGHA.1216@.TK2MSFTNGP03.phx.gbl...
>> How can I get similar results from a query like this >
>> SELECT au_lname, state
>> FROM authors
>> WHERE state IN ('CA', 'IN', 'MD')
>> Except to replace ('CA', 'IN', 'MD') With a field that will have a
>> similar format'
>> The Field is Misc it's contents are (100, 101, 102) and so on. I need to
>> display a row for each occurrence of 3 digits in that field and replacing
>> ('CA', 'IN', 'MD') with something like (SELECT au_id FROM titleauthor
>> WHERE royaltyper < 50) is not the same thing..
>> I'm thinking I need some type of variable length array, but I am out of
>> practice and not sure, can some one please help me..
> I'm not completely following here, but you can use either an IN clause or
> a WHERE EXISTS clause.
> Perhaps something like:
> SELECT au_id
> FROM titleauthor
> WHERE SomeValue IN (SELECT myLookupValues FROM sometable WHERE
> somecondition)
>
> Rick Sawtell
> MCT, MCSD, MCDBA
>
>|||WANNABE wrote:
> Thanks for you response Rick, but I think what you have described below is
> what I have been trying to get to work. When I run this >>
> SELECT au_lname, state
> FROM authors
> WHERE state IN ('CA', 'IN', 'MD')
> I get a long list of records. I would like to get the same long list of
> records by running something like the following query, AFTER I HAVE MODIFIED
> THE stores TABLE TO INCLUDE THE stid FIELD and ENTERED THE VALUE (CA, IN,
> MD) into that field for the record where stor_id is equal to 7067.
> When I run this next query AFTER I have made the modifications described
> above, I get only column headers>>
> SELECT au_lname, state
> FROM authors
> WHERE state IN
> (SELECT stid
> FROM stores
> WHERE stor_id = '7067')
> This is all done in testing using the PUBS database, and here are the
> queries used to modify that db
> alter table pubs.dbo.stores add stid char(50)
> UPDATE stores
> SET [stid] = '(CA, IN, MD)'
> where stor_id = '7067'
You're looking for a way to parse a comma-delimited string and use its
elements in a query. Start by reading this:
http://www.realsqlguy.com/serendipity/archives/4-Parse-A-Delimited-String-Into-A-Table.html
Tracy McKibben
MCDBA
http://www.realsqlguy.com|||Thanks Tracy, but that is the opposite of what I am trying to do, which is
to parse a delimited string from a table. Can someone tell me how'
"Tracy McKibben" <tracy@.realsqlguy.com> wrote in message
news:44E31A57.9030809@.realsqlguy.com...
> WANNABE wrote:
>> Thanks for you response Rick, but I think what you have described below
>> is what I have been trying to get to work. When I run this >>
>> SELECT au_lname, state
>> FROM authors
>> WHERE state IN ('CA', 'IN', 'MD')
>> I get a long list of records. I would like to get the same long list of
>> records by running something like the following query, AFTER I HAVE
>> MODIFIED THE stores TABLE TO INCLUDE THE stid FIELD and ENTERED THE VALUE
>> (CA, IN, MD) into that field for the record where stor_id is equal to
>> 7067.
>> When I run this next query AFTER I have made the modifications described
>> above, I get only column headers>>
>> SELECT au_lname, state
>> FROM authors
>> WHERE state IN
>> (SELECT stid
>> FROM stores
>> WHERE stor_id = '7067')
>> This is all done in testing using the PUBS database, and here are the
>> queries used to modify that db
>> alter table pubs.dbo.stores add stid char(50)
>> UPDATE stores
>> SET [stid] = '(CA, IN, MD)'
>> where stor_id = '7067'
> You're looking for a way to parse a comma-delimited string and use its
> elements in a query. Start by reading this:
> http://www.realsqlguy.com/serendipity/archives/4-Parse-A-Delimited-String-Into-A-Table.html
>
> --
> Tracy McKibben
> MCDBA
> http://www.realsqlguy.com

Query Question

I have a query that I am not sure how to write.
I need to get the value of a column where that column's value happens more
than once AND a date column has the same date.
for instance:
ColA ColB
--
ValA 1/1/2003
ValA 1/1/2003
ValX 1/1/2003
I need to find all values from ColA where there is another row with the same
value in ColA and ColB (in this case the query should return ValA).
?SELECT DISTINCT colA
FROM Sometable
GROUP BY colA, colB
HAVING COUNT(*)>1
--
David Portas
--
Please reply only to the newsgroup
--|||Thanks David,
Makes sense and did the trick
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:-PWdnfOhm6CPriCi4p2dnA@.giganews.com...
> SELECT DISTINCT colA
> FROM Sometable
> GROUP BY colA, colB
> HAVING COUNT(*)>1
> --
> David Portas
> --
> Please reply only to the newsgroup
> --
>|||select cola from table_name
group by cola,colb
having count(*) >1
_______________________
"A" <agarrettbNOSPAM@.hotmail.com> wrote in message
news:OvXOcu6rDHA.1764@.TK2MSFTNGP10.phx.gbl...
> I have a query that I am not sure how to write.
> I need to get the value of a column where that column's value happens more
> than once AND a date column has the same date.
> for instance:
> ColA ColB
> --
> ValA 1/1/2003
> ValA 1/1/2003
> ValX 1/1/2003
> I need to find all values from ColA where there is another row with the
same
> value in ColA and ColB (in this case the query should return ValA).
> ?
>
>

Query Question

Greetings,
I am new to SQL Server and am trying to write a query for an application I
am working on. The table I am working with has three dollar amounts in
seperate columns that are prices on the same product from multiple
distributors. I am having trouble building a query that does a comparison on
these fields and returns a list of records based upon the lowest dollar amount
The results would be then used to populate a new table using only the lowest
price as returned from the SELECT statement
Is there someone who might be able to point me to some sample code that I
could use to help me figure out how this could be written
Thanks,
Joe.SELECT col1, col2, col3, ...
(SELECT MIN(price)
FROM
(SELECT price1 AS price UNION ALL
SELECT price2 UNION ALL
SELECT price3) AS T) AS min_price
FROM YourTable
The three price columns collectively represent a "repeating group". In
relational design this is a serious error and the difficulty you are having
is a consequence of the design problem. Hopefully your intention is to fix
this.
--
David Portas
SQL Server MVP
--|||David,
I assume that MIN will still work in the same manner if the price values
being compared are in seperate tables. I am working on different ways to get
rid of the repeating problem.
Thanks for your help
Joe.
"David Portas" wrote:
> SELECT col1, col2, col3, ...
> (SELECT MIN(price)
> FROM
> (SELECT price1 AS price UNION ALL
> SELECT price2 UNION ALL
> SELECT price3) AS T) AS min_price
> FROM YourTable
> The three price columns collectively represent a "repeating group". In
> relational design this is a serious error and the difficulty you are having
> is a consequence of the design problem. Hopefully your intention is to fix
> this.
> --
> David Portas
> SQL Server MVP
> --
>
>|||MIN retrieves the lowest non-NULL value of a set. If you can join the
additional table into the query then you should be able to make use of MIN.
My point about your design was that it would be easier and more efficient to
do this if your design was correctly normalized.
--
David Portas
SQL Server MVP
--

query question

This is my current query that I have in an App I wrote:
MySQL = "select DateEntered,Shipper,PickupDate,PUTime,City, State, Zip,
Consignee, Destination, DState, DZip, PickupNumber, ShippersNumber,
PONumber, Consignee_Ref_Number, Weight, Number_Packages, Carrier,
Carrier_Number, Trailer_Number, ApptDate, ApptTime, IDFProNumber,
DeliveredDate, DeliveredTime, FreightCharges, TransitTime, Comments,
LastUpdate, lastcomment from IntermodalTracingMasterFile where " &
tmpMyShippers & " Order by [" & strSort & "] desc "
This works fine.
I need to modify it a little I need to have one query that will return when
the DeliveredDate is empty
and anohter query to return the ones that have somethign in the
DeliveredDate field.
ThanksOn Wed, 17 Nov 2004 15:58:44 -0800, johnfli wrote:
>This is my current query that I have in an App I wrote:
(snip)
>I need to modify it a little I need to have one query that will return when
>the DeliveredDate is empty
>and anohter query to return the ones that have somethign in the
>DeliveredDate field.
Hi johnfli,
Add "WHERE DeliveredDate IS NULL" or "WHERE DeliveredDate IS NOT NULL"
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Query Question

my data looks like the following
111 0 01/01/2007
111 0 02/01/2007
222 0 04/01/2007
222 0 05/01/2007
555 1 06/01/2007
666 0 06/01/2007
how can i retrieve the following?
111 0 01/01/2007
222 0 04/01/2007
555 1 06/01/2007
666 0 06/01/2007
my goal is to retrive distinct cols 1 and 2, and then the earliest date in
col 3 for distinct records in cols 1 and 2?
any suggestions? I tried different ways of using FIRST, but was
unsuccessful.
Thanks in advance.try something like:
select ID, Nb, Date
from table T
where Date = (Select min(Date) from Table t2
where t.id = t2.id)
"Jeff" <findjeffajob@.emailias.com> wrote in message
news:0468D8F6-CABC-4758-A5E3-864723DDD630@.microsoft.com...
> my data looks like the following
> 111 0 01/01/2007
> 111 0 02/01/2007
> 222 0 04/01/2007
> 222 0 05/01/2007
> 555 1 06/01/2007
> 666 0 06/01/2007
> how can i retrieve the following?
> 111 0 01/01/2007
> 222 0 04/01/2007
> 555 1 06/01/2007
> 666 0 06/01/2007
> my goal is to retrive distinct cols 1 and 2, and then the earliest date in
> col 3 for distinct records in cols 1 and 2?
> any suggestions? I tried different ways of using FIRST, but was
> unsuccessful.
> Thanks in advance.|||"Jeff" <findjeffajob@.emailias.com> wrote in message
news:0468D8F6-CABC-4758-A5E3-864723DDD630@.microsoft.com...
> my data looks like the following
> 111 0 01/01/2007
> 111 0 02/01/2007
> 222 0 04/01/2007
> 222 0 05/01/2007
> 555 1 06/01/2007
> 666 0 06/01/2007
> how can i retrieve the following?
> 111 0 01/01/2007
> 222 0 04/01/2007
> 555 1 06/01/2007
> 666 0 06/01/2007
> my goal is to retrive distinct cols 1 and 2, and then the earliest date in
> col 3 for distinct records in cols 1 and 2?
> any suggestions? I tried different ways of using FIRST, but was
> unsuccessful.
> Thanks in advance.
This works for me:
CREATE TABLE tbl (col1 INT, col2 INT, col3 DATETIME);
INSERT INTO tbl VALUES (111, 0, '20070101');
INSERT INTO tbl VALUES (111, 0, '20070201');
INSERT INTO tbl VALUES (222, 0, '20070401');
INSERT INTO tbl VALUES (222, 0, '20070501');
INSERT INTO tbl VALUES (555, 1, '20070601');
INSERT INTO tbl VALUES (666, 0, '20070601');
SELECT col1, col2, MIN(col3) col3
FROM tbl
GROUP BY col1, col2
ORDER BY col1, col2 ;
col1 col2 col3
-- -- --
111 0 2007-01-01 00:00:00.000
222 0 2007-04-01 00:00:00.000
555 1 2007-06-01 00:00:00.000
666 0 2007-06-01 00:00:00.000
(4 row(s) affected)
David Portassql

query question

Hi I have 3 tables and am wondering if there is a way to do this. I would
like a qerry that returns data for a data item but will return only the # of
records for the event and not the destination. For example if the query
returns data for Data ID 4
I would want to see as the results.
Data name event destination
report recieved office
report intransit frontdesk
Even though there are 3 destinations I would like to only list the first 2
and base the number of records returned on the number of events. Thanks.
table1 event
****************************************
**
*pri key Count * foriegn key Data ID * event *
* 1 * 3 * arrived *
* 2 * 4 * recieved *
* 3 * 4 * intransit *
****************************************
**
table2 data item
*****************************
* Pri key Data ID * Data name *
* 3 * email *
* 4 * report *
*****************************
table3- destination-note no prim key
**********************************
* Data ID * destination *
* 4 * office *
* 4 * frontdesk *
* 4 * mailroom *
**********************************
Paul G
Software engineer.Hi Paul
See http://www.aspfaq.com/etiquette.asp?id=5006 on how to post useful DDL
and example data in a usable format, also posting the expected output from
the data provided would be helpful e.g.
CREATE TABLE [event] ( [Count] int, [Data ID] int, [event] v
archar(30) )
INSERT INTO [event] ( [Count], [Data ID], [event] )
SELECT 1, 3, 'arrived'
UNION ALL SELECT 2, 4, 'recieved'
UNION ALL SELECT 3, 4, 'intransit'
CREATE TABLE [data item] ( [Data ID] int, [Data name] varchar(30
) )
INSERT INTO [data item] ( [Data ID], [Data name] )
SELECT 3, 'email'
UNION ALL SELECT 4, 'report'
CREATE TABLE destination ( [Data ID] int, destination varchar(30) )
INSERT INTO destination ( [Data ID], destination )
SELECT 4, 'office'
UNION ALL SELECT 4, 'frontdesk'
UNION ALL SELECT 4, 'mailroom'
There is no way to easily distinguish your destinations e.g
SELECT d.[Data name], e.[Event], f.destination
FROM [Data Item] d
JOIN [Event] e ON d.[Data Id] = e.[Data Id]
JOIN destination f ON f.[Data Id] = e.[Data Id]
ORDER BY e.[Count] DESC
Returns
Data name Event destination
-- -- --
--
report intransit office
report intransit frontdesk
report intransit mailroom
report recieved office
report recieved mailroom
report recieved frontdesk
(6 row(s) affected)
Limiting this to top 2
SELECT TOP 2 d.[Data name], e.[Event], f.destination
FROM [Data Item] d
JOIN [Event] e ON d.[Data Id] = e.[Data Id]
JOIN destination f ON f.[Data Id] = e.[Data Id]
ORDER BY e.[Count] DESC
Returns
Data name Event destination
-- -- --
--
report intransit office
report intransit frontdesk
(2 row(s) affected)
You could give destination alphabetical rank such as
SELECT f.[Data ID], f.destination,
( SELECT COUNT(*) FROM destination b WHERE f..destination <
b.destination )+1 AS RANK
FROM destination f
This may then allow you to pick different destinations by joining to the
event count (you may have to rank these to get similar number ranges.
SELECT TOP 2 d.[Data name], e.[Event], g.destination
FROM [Data Item] d
JOIN [Event] e ON d.[Data Id] = e.[Data Id]
JOIN ( SELECT f.[Data ID],
f.destination,
( SELECT COUNT(*) FROM destination b WHERE f.destination < b.destination )+1
AS RANK
FROM destination f
) g ON g.[Data Id] = e.[Data Id] AND e.[count] = g.rank
ORDER BY e.[Count] DESC
Data name Event destination
-- -- --
--
report intransit frontdesk
report recieved mailroom
(2 row(s) affected)
John
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:7FC06E5C-8E29-4F97-9268-F7E9A6878C03@.microsoft.com...
> Hi I have 3 tables and am wondering if there is a way to do this. I would
> like a qerry that returns data for a data item but will return only the #
> of
> records for the event and not the destination. For example if the query
> returns data for Data ID 4
> I would want to see as the results.
> Data name event destination
> report recieved office
> report intransit frontdesk
> Even though there are 3 destinations I would like to only list the first 2
> and base the number of records returned on the number of events. Thanks.
> table1 event
> ****************************************
**
> *pri key Count * foriegn key Data ID * event *
> * 1 * 3 * arrived
> *
> * 2 * 4 * recieved
> *
> * 3 * 4 * intransit
> *
> ****************************************
**
> table2 data item
> *****************************
> * Pri key Data ID * Data name *
> * 3 * email *
> * 4 * report *
> *****************************
> table3- destination-note no prim key
> **********************************
> * Data ID * destination *
> * 4 * office *
> * 4 * frontdesk *
> * 4 * mailroom *
> **********************************
>
> --
> Paul G
> Software engineer.|||hi thanks for the response. Does seem quite useful to use DDL, will do this
in the future. Unfortunately I will net be able to use a constant for the #
of records returned as the number of records returned for each data item wil
l
not be the destinations but the number of events for each data item. Guess
I
will probably use 2 queries the first one getting the # of events for each
data item and the second returning the data name, event and destination and
using the TOP or ROWCOUNT to limit the # of records returned. Thanks again,
Paul.
--
Paul G
Software engineer.
"John Bell" wrote:

> Hi Paul
> See http://www.aspfaq.com/etiquette.asp?id=5006 on how to post useful DDL
> and example data in a usable format, also posting the expected output from
> the data provided would be helpful e.g.
> CREATE TABLE [event] ( [Count] int, [Data ID] int, [event]
varchar(30) )
> INSERT INTO [event] ( [Count], [Data ID], [event] )
> SELECT 1, 3, 'arrived'
> UNION ALL SELECT 2, 4, 'recieved'
> UNION ALL SELECT 3, 4, 'intransit'
> CREATE TABLE [data item] ( [Data ID] int, [Data name] varchar(
30) )
> INSERT INTO [data item] ( [Data ID], [Data name] )
> SELECT 3, 'email'
> UNION ALL SELECT 4, 'report'
>
> CREATE TABLE destination ( [Data ID] int, destination varchar(30) )
> INSERT INTO destination ( [Data ID], destination )
> SELECT 4, 'office'
> UNION ALL SELECT 4, 'frontdesk'
> UNION ALL SELECT 4, 'mailroom'
>
> There is no way to easily distinguish your destinations e.g
> SELECT d.[Data name], e.[Event], f.destination
> FROM [Data Item] d
> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> JOIN destination f ON f.[Data Id] = e.[Data Id]
> ORDER BY e.[Count] DESC
> Returns
> Data name Event destination
> -- -- --
--
> report intransit office
> report intransit frontdesk
> report intransit mailroom
> report recieved office
> report recieved mailroom
> report recieved frontdesk
> (6 row(s) affected)
>
> Limiting this to top 2
> SELECT TOP 2 d.[Data name], e.[Event], f.destination
> FROM [Data Item] d
> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> JOIN destination f ON f.[Data Id] = e.[Data Id]
> ORDER BY e.[Count] DESC
> Returns
> Data name Event destination
> -- -- --
--
> report intransit office
> report intransit frontdesk
> (2 row(s) affected)
> You could give destination alphabetical rank such as
>
> SELECT f.[Data ID], f.destination,
> ( SELECT COUNT(*) FROM destination b WHERE f..destination <
> b.destination )+1 AS RANK
> FROM destination f
> This may then allow you to pick different destinations by joining to the
> event count (you may have to rank these to get similar number ranges.
> SELECT TOP 2 d.[Data name], e.[Event], g.destination
> FROM [Data Item] d
> JOIN [Event] e ON d.[Data Id] = e.[Data Id]
> JOIN ( SELECT f.[Data ID],
> f.destination,
> ( SELECT COUNT(*) FROM destination b WHERE f.destination < b.destination )
+1
> AS RANK
> FROM destination f
> ) g ON g.[Data Id] = e.[Data Id] AND e.[count] = g.rank
> ORDER BY e.[Count] DESC
> Data name Event destination
> -- -- --
--
> report intransit frontdesk
> report recieved mailroom
> (2 row(s) affected)
> John
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:7FC06E5C-8E29-4F97-9268-F7E9A6878C03@.microsoft.com...
>
>|||Hi
SQL 2005 allows top to take a variable, but that may not be any use to
yourself. You may be able to use a having clause if you can formulate the
number of rows required and then use the ranking as the tested value.
John
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:0881ACE2-979C-425A-B53B-3627D46A6A05@.microsoft.com...[vbcol=seagreen]
> hi thanks for the response. Does seem quite useful to use DDL, will do
> this
> in the future. Unfortunately I will net be able to use a constant for the
> #
> of records returned as the number of records returned for each data item
> will
> not be the destinations but the number of events for each data item.
> Guess I
> will probably use 2 queries the first one getting the # of events for each
> data item and the second returning the data name, event and destination
> and
> using the TOP or ROWCOUNT to limit the # of records returned. Thanks
> again,
> Paul.
> --
> Paul G
> Software engineer.
>
> "John Bell" wrote:
>|||ok thanks for the additional information. I guess I could use the ROWCOUNT
which does take a variable. Hopefully we will upgrade to SQL 2005 but it
will be awhile.
--
Paul G
Software engineer.
"John Bell" wrote:

> Hi
> SQL 2005 allows top to take a variable, but that may not be any use to
> yourself. You may be able to use a having clause if you can formulate the
> number of rows required and then use the ranking as the tested value.
> John
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:0881ACE2-979C-425A-B53B-3627D46A6A05@.microsoft.com...
>
>

query question

This is my current query that I have in an App I wrote:
MySQL = "select DateEntered,Shipper,PickupDate,PUTime,Ci
ty, State, Zip,
Consignee, Destination, DState, DZip, PickupNumber, ShippersNumber,
PONumber, Consignee_Ref_Number, Weight, Number_Packages, Carrier,
Carrier_Number, Trailer_Number, ApptDate, ApptTime, IDFProNumber,
DeliveredDate, DeliveredTime, FreightCharges, TransitTime, Comments,
LastUpdate, lastcomment from IntermodalTracingMasterFile where " &
tmpMyShippers & " Order by [" & strSort & "] desc "
This works fine.
I need to modify it a little I need to have one query that will return when
the DeliveredDate is empty
and anohter query to return the ones that have somethign in the
DeliveredDate field.
ThanksOn Wed, 17 Nov 2004 15:58:44 -0800, johnfli wrote:

>This is my current query that I have in an App I wrote:
(snip)
>I need to modify it a little I need to have one query that will return when
>the DeliveredDate is empty
>and anohter query to return the ones that have somethign in the
>DeliveredDate field.
Hi johnfli,
Add "WHERE DeliveredDate IS NULL" or "WHERE DeliveredDate IS NOT NULL"
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Query Question

How can I get similar results from a query like this >
SELECT au_lname, state
FROM authors
WHERE state IN ('CA', 'IN', 'MD')
Except to replace ('CA', 'IN', 'MD') With a field that will have a similar
format'
The Field is Misc it's contents are (100, 101, 102) and so on. I need to
display a row for each occurrence of 3 digits in that field and replacing
('CA', 'IN', 'MD') with something like (SELECT au_id FROM titleauthor
WHERE royaltyper < 50) is not the same thing..
I'm thinking I need some type of variable length array, but I am out of
practice and not sure, can some one please help me.."WANNABE" <breichenbach AT istate DOT com> wrote in message
news:e34iWyJwGHA.1216@.TK2MSFTNGP03.phx.gbl...
> How can I get similar results from a query like this >
> SELECT au_lname, state
> FROM authors
> WHERE state IN ('CA', 'IN', 'MD')
> Except to replace ('CA', 'IN', 'MD') With a field that will have a similar
> format'
> The Field is Misc it's contents are (100, 101, 102) and so on. I need to
> display a row for each occurrence of 3 digits in that field and replacing
> ('CA', 'IN', 'MD') with something like (SELECT au_id FROM titleauthor
> WHERE royaltyper < 50) is not the same thing..
> I'm thinking I need some type of variable length array, but I am out of
> practice and not sure, can some one please help me..
>
I'm not completely following here, but you can use either an IN clause or a
WHERE EXISTS clause.
Perhaps something like:
SELECT au_id
FROM titleauthor
WHERE SomeValue IN (SELECT myLookupValues FROM sometable WHERE
somecondition)
Rick Sawtell
MCT, MCSD, MCDBA|||Thanks for you response Rick, but I think what you have described below is
what I have been trying to get to work. When I run this >>
SELECT au_lname, state
FROM authors
WHERE state IN ('CA', 'IN', 'MD')
I get a long list of records. I would like to get the same long list of
records by running something like the following query, AFTER I HAVE MODIFIED
THE stores TABLE TO INCLUDE THE stid FIELD and ENTERED THE VALUE (CA, IN,
MD) into that field for the record where stor_id is equal to 7067.
When I run this next query AFTER I have made the modifications described
above, I get only column headers>>
SELECT au_lname, state
FROM authors
WHERE state IN
(SELECT stid
FROM stores
WHERE stor_id = '7067')
This is all done in testing using the PUBS database, and here are the
queries used to modify that db
alter table pubs.dbo.stores add stid char(50)
UPDATE stores
SET [stid] = '(CA, IN, MD)'
where stor_id = '7067'
=======================================
"Rick Sawtell" <Quickening@.msn.com> wrote in message
news:%23OwzMOKwGHA.1288@.TK2MSFTNGP02.phx.gbl...
> "WANNABE" <breichenbach AT istate DOT com> wrote in message
> news:e34iWyJwGHA.1216@.TK2MSFTNGP03.phx.gbl...
> I'm not completely following here, but you can use either an IN clause or
> a WHERE EXISTS clause.
> Perhaps something like:
> SELECT au_id
> FROM titleauthor
> WHERE SomeValue IN (SELECT myLookupValues FROM sometable WHERE
> somecondition)
>
> Rick Sawtell
> MCT, MCSD, MCDBA
>
>|||WANNABE wrote:
> Thanks for you response Rick, but I think what you have described below is
> what I have been trying to get to work. When I run this >>
> SELECT au_lname, state
> FROM authors
> WHERE state IN ('CA', 'IN', 'MD')
> I get a long list of records. I would like to get the same long list of
> records by running something like the following query, AFTER I HAVE MODIFI
ED
> THE stores TABLE TO INCLUDE THE stid FIELD and ENTERED THE VALUE (CA, IN,
> MD) into that field for the record where stor_id is equal to 7067.
> When I run this next query AFTER I have made the modifications described
> above, I get only column headers>>
> SELECT au_lname, state
> FROM authors
> WHERE state IN
> (SELECT stid
> FROM stores
> WHERE stor_id = '7067')
> This is all done in testing using the PUBS database, and here are the
> queries used to modify that db
> alter table pubs.dbo.stores add stid char(50)
> UPDATE stores
> SET [stid] = '(CA, IN, MD)'
> where stor_id = '7067'
You're looking for a way to parse a comma-delimited string and use its
elements in a query. Start by reading this:
http://www.realsqlguy.com/serendipi...r />
able.html
Tracy McKibben
MCDBA
http://www.realsqlguy.com|||Thanks Tracy, but that is the opposite of what I am trying to do, which is
to parse a delimited string from a table. Can someone tell me how'
"Tracy McKibben" <tracy@.realsqlguy.com> wrote in message
news:44E31A57.9030809@.realsqlguy.com...
> WANNABE wrote:
> You're looking for a way to parse a comma-delimited string and use its
> elements in a query. Start by reading this:
> http://www.realsqlguy.com/serendipi.../>
-Table.html
>
> --
> Tracy McKibben
> MCDBA
> http://www.realsqlguy.com

Query Question

Greetings,
I am new to SQL Server and am trying to write a query for an application I
am working on. The table I am working with has three dollar amounts in
seperate columns that are prices on the same product from multiple
distributors. I am having trouble building a query that does a comparison on
these fields and returns a list of records based upon the lowest dollar amou
nt
The results would be then used to populate a new table using only the lowest
price as returned from the SELECT statement
Is there someone who might be able to point me to some sample code that I
could use to help me figure out how this could be written
Thanks,
Joe.SELECT col1, col2, col3, ...
(SELECT MIN(price)
FROM
(SELECT price1 AS price UNION ALL
SELECT price2 UNION ALL
SELECT price3) AS T) AS min_price
FROM YourTable
The three price columns collectively represent a "repeating group". In
relational design this is a serious error and the difficulty you are having
is a consequence of the design problem. Hopefully your intention is to fix
this.
David Portas
SQL Server MVP
--|||David,
I assume that MIN will still work in the same manner if the price values
being compared are in seperate tables. I am working on different ways to get
rid of the repeating problem.
Thanks for your help
Joe.
"David Portas" wrote:

> SELECT col1, col2, col3, ...
> (SELECT MIN(price)
> FROM
> (SELECT price1 AS price UNION ALL
> SELECT price2 UNION ALL
> SELECT price3) AS T) AS min_price
> FROM YourTable
> The three price columns collectively represent a "repeating group". In
> relational design this is a serious error and the difficulty you are havin
g
> is a consequence of the design problem. Hopefully your intention is to fix
> this.
> --
> David Portas
> SQL Server MVP
> --
>
>|||MIN retrieves the lowest non-NULL value of a set. If you can join the
additional table into the query then you should be able to make use of MIN.
My point about your design was that it would be easier and more efficient to
do this if your design was correctly normalized.
David Portas
SQL Server MVP
--

query question

I saw a query in which there was a expression
SELECT
case when credit_flag&1 = 1 then 1 else 0 end as credit_default_flag1,
case when credit_flag&2 = 2 then 1 else 0 end as credit_default_flag2,
case when credit_flag&4 = 4 then 1 else 0 end as credit_default_flag3
FROM ...
What happens when we do column & 1, column & 2
THanks
Sanjay& is the bit-wise AND operator in T-SQL. So credit_flag &
1 will return 1 on the first bit only when the first bit
from the right (of credit_flag) is set to 1. And
credit_flag & 4 will return 1 on the third bit (thus
decimal 4) only when the third bit from the right (of
credit_flag) is set to 1.
Linchi
quote:

>--Original Message--
>I saw a query in which there was a expression
>SELECT
>case when credit_flag&1 = 1 then 1 else 0 end as

credit_default_flag1,
quote:
ed">
>case when credit_flag&2 = 2 then 1 else 0 end as

credit_default_flag2,
quote:
ed">
>case when credit_flag&4 = 4 then 1 else 0 end as

credit_default_flag3
quote:
d">
>FROM ...
>
>What happens when we do column & 1, column & 2
>THanks
>Sanjay
>.
>
|||HI Linchi
Do you have some white paper or document which would explain more about thes
e bit-wise operations
I think you explained what the result would be but i am not clear how bit-wi
se operations work at first place
Thanks|||The bit-wise AND operator (also OR and XOR) is supported
in most, if not all, programming languages. You can pick
up any programming tutorial book and find information on
the bit-wise operations. You can also find the info in the
SQL Server Books Online.
Linchi
quote:

>--Original Message--
>HI Linchi
>Do you have some white paper or document which would

explain more about these bit-wise operations
quote:

>I think you explained what the result would be but i am

not clear how bit-wise operations work at first place
quote:

>Thanks
>.
>
sql

Query Question

I have a question that I will illustrate with the script below. As you can
see there two tables, airlines and routes. Each airline has a customer_rank
that indicates the preferred airline of the customer ie 1 is most preferred.
Each route has a name, cost and duration.
What I would like to do is write a query that returns one row for each route
with the columns : airline, cost and duration. I would like the airline
column to be based on the preferred carrier, irrespective of the cost and
duration.
Can someone please stop my head spinning?
Thanks, Tad
CREATE TABLE [dbo].[Airlines] (
[Airline] [char] (10) PRIMARY KEY,
[Customer_Rank] [tinyint] NOT NULL
)
CREATE TABLE [dbo].[Routes] (
[ID] [int] IDENTITY (1, 1) PRIMARY KEY,
[Airline] [char] (10) NOT NULL REFERENCES Airlines(Airline),
[Route] [char] (10) NOT NULL ,
[Cost] [numeric](18, 0) NOT NULL ,
[Duration] [numeric](18, 0) NOT NULL
)
INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
VALUES('BOAC',3)
INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
VALUES('TWA',2)
INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
VALUES('United',1)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Du
ration])
VALUES('BOAC', 'A2B', 150, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Du
ration])
VALUES('TWA', 'A2C', 200, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Du
ration])
VALUES('BOAC', 'B2C', 200, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Du
ration])
VALUES('United', 'A2B', 200, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Du
ration])
VALUES('United', 'D2E', 300, 3)
INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [Du
ration])
VALUES('BOAC', 'B2D', 300, 3)first of all you want to know which airline is the preferred carrier
for each route, so you have to inner join the two tables and find the
airline with the lowest (if highest substitute min by max) rank:
select route, min(customer_rank) rank
from routes r, airlines a
where a.airline=r.airline
group by route
with this query you get the the ranking of the preferred airline per
route. This output has to be inner joined with the airlines and routes
to get the desired result
select *
from airlines a,
routes r,
(
select route, min(customer_rank) rank
from routes r, airlines a
where a.airline=r.airline
group by route
) p
where a.customer_rank = p.rank
and r.route = p.route
and a.airline = r.airline
if you want to avoid an inner table (the stuff between (...)p) you
could create a view, but you will learn that in your next class.|||Hi
Thanks for the DDL and Example data, showing your expected results would
also be nice. You can either use a subquery in the where clause or a derived
table such as
SELECT A.[Customer_Rank],
R.[ID], R.[Airline], R.[Route], R.[Cost], R.[Duration]
FROM [dbo].[Routes] R
JOIN [dbo].[Airlines] A ON A.[Airline] = R.[Airline]
JOIN ( SELECT MIN(E.[Customer_Rank]) AS [Customer_Rank], D.[Rout
e]
FROM [dbo].[Routes] D
JOIN [dbo].[Airlines] E ON D.[Airline] = E.[Airline]
GROUP BY D.[Route] ) F ON F.[Customer_Rank] = A.[Customer_Rank]
AND
F.[Route] = R.[Route]
ORDER BY R.[Route], A.[Customer_Rank]
John
"Tadwick" wrote:

> I have a question that I will illustrate with the script below. As you ca
n
> see there two tables, airlines and routes. Each airline has a customer_ra
nk
> that indicates the preferred airline of the customer ie 1 is most preferre
d.
> Each route has a name, cost and duration.
> What I would like to do is write a query that returns one row for each rou
te
> with the columns : airline, cost and duration. I would like the airline
> column to be based on the preferred carrier, irrespective of the cost and
> duration.
> Can someone please stop my head spinning?
> Thanks, Tad
>
> CREATE TABLE [dbo].[Airlines] (
> [Airline] [char] (10) PRIMARY KEY,
> [Customer_Rank] [tinyint] NOT NULL
> )
> CREATE TABLE [dbo].[Routes] (
> [ID] [int] IDENTITY (1, 1) PRIMARY KEY,
> [Airline] [char] (10) NOT NULL REFERENCES Airlines(Airline),
> [Route] [char] (10) NOT NULL ,
> [Cost] [numeric](18, 0) NOT NULL ,
> [Duration] [numeric](18, 0) NOT NULL
> )
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('BOAC',3)
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('TWA',2)
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('United',1)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('BOAC', 'A2B', 150, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('TWA', 'A2C', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('BOAC', 'B2C', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('United', 'A2B', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('United', 'D2E', 300, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('BOAC', 'B2D', 300, 3)|||Nite4Hawks and John,
You are both awesome. I am amazed to get responses with two different
techniques in such a short time. Are there pros and cons of the correlated
subquery vs derived table methods?
Thanks again, Tad
"Tadwick" wrote:

> I have a question that I will illustrate with the script below. As you ca
n
> see there two tables, airlines and routes. Each airline has a customer_ra
nk
> that indicates the preferred airline of the customer ie 1 is most preferre
d.
> Each route has a name, cost and duration.
> What I would like to do is write a query that returns one row for each rou
te
> with the columns : airline, cost and duration. I would like the airline
> column to be based on the preferred carrier, irrespective of the cost and
> duration.
> Can someone please stop my head spinning?
> Thanks, Tad
>
> CREATE TABLE [dbo].[Airlines] (
> [Airline] [char] (10) PRIMARY KEY,
> [Customer_Rank] [tinyint] NOT NULL
> )
> CREATE TABLE [dbo].[Routes] (
> [ID] [int] IDENTITY (1, 1) PRIMARY KEY,
> [Airline] [char] (10) NOT NULL REFERENCES Airlines(Airline),
> [Route] [char] (10) NOT NULL ,
> [Cost] [numeric](18, 0) NOT NULL ,
> [Duration] [numeric](18, 0) NOT NULL
> )
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('BOAC',3)
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('TWA',2)
> INSERT INTO [dbo].[Airlines]([Airline], [Customer_Rank])
> VALUES('United',1)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('BOAC', 'A2B', 150, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('TWA', 'A2C', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('BOAC', 'B2C', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('United', 'A2B', 200, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('United', 'D2E', 300, 3)
> INSERT INTO dbo.[Routes]([Airline], [Route], [Cost], [
Duration])
> VALUES('BOAC', 'B2D', 300, 3)

Query question

I'm having a problem with a query where it is not doing
what I would like for it to do. I have a Call table
where helpdesk calls get logged. I then have a Severity
table that stores the severity level of the call. Each
call must have a severity of 1,2 or 3.
I want to query the database and return Call counts for
each of the severity (1,2 and 3) given a date period.
For example, in the month of January, there were a total
of 2 severity 1 calls, 25 severity 2, and 50 severity 3.
My output would look like this.
Severity CallCount
-- --
1 2
2 25
3 50
Now, for the month of February, say there were zero(0)
severity 1 calls, 30 severity 2, and 77 severity 3, I
want my output to look like this
Severity CallCount
-- --
1 0
2 30
3 77
....However, my problem is that I do not get a record
for severity 1 cuz there are no calls for that month.
My query is below. What am I doing wrong? There is no
relationship between the two tables. The Severity table
just stores detail information regarding each of the
severities such as required response time and repair time
to fix a problem based on the severity. Please help.
SELECT
Severity.Severity,
Severity.ResponseTime,
Severity.RepairTime,
Count(Call.CallNo) As CallCount
FROM
Severity
Left Join Call
On Severity.Severity = Call.Severity
WHERE
Call.DateTimeSubmitted Between '01/01/2004'
and '01/31/2004'
AND
Call.Status <> 'CANCELLED'
GROUP BY
Severity.Severity,
Severity.ResponseTime,
Severity.RepairTime,
Order By
Severity.Severity
TIA,
VicPut Your WHERE criteria into the ON clause:
SELECT S.severity, S.responsetime, S.repairtime, COUNT(C.callno) AS
callcount
FROM Severity AS S
LEFT JOIN Call AS C
ON S.Severity = C.Severity
AND C.datetimesubmitted >= '20040101'
AND C.datetimesubmitted < '20050101'
AND C.status <> 'CANCELLED'
GROUP BY S.severity, S.responsetime, S.repairtime
ORDER BY S.Severity
As above, you may want to use >= and < for the date range rather than
BETWEEN. The code you posted will exclude rows where call was submitted on
2004-12-31 but the datetimesubmitted was timed after midnight.
Hope this helps.
David Portas
SQL Server MVP
--|||REPOST: I misread the dates
Put Your WHERE criteria into the ON clause:
SELECT S.severity, S.responsetime, S.repairtime, COUNT(C.callno) AS
callcount
FROM Severity AS S
LEFT JOIN Call AS C
ON S.Severity = C.Severity
AND C.datetimesubmitted >= '20040101'
AND C.datetimesubmitted < '20040201'
AND C.status <> 'CANCELLED'
GROUP BY S.severity, S.responsetime, S.repairtime
ORDER BY S.Severity
As above, you may want to use >= and < for the date range rather than
BETWEEN. The code you posted will exclude rows where call was submitted on
2004-01-31 but the datetimesubmitted was timed after midnight.
Hope this helps.
David Portas
SQL Server MVP
--
David Portas
SQL Server MVP
--
"Vic" <vduran@.specpro-inc.com> wrote in message
news:91cb01c4332b$51b42fb0$a301280a@.phx.gbl...
> I'm having a problem with a query where it is not doing
> what I would like for it to do. I have a Call table
> where helpdesk calls get logged. I then have a Severity
> table that stores the severity level of the call. Each
> call must have a severity of 1,2 or 3.
> I want to query the database and return Call counts for
> each of the severity (1,2 and 3) given a date period.
> For example, in the month of January, there were a total
> of 2 severity 1 calls, 25 severity 2, and 50 severity 3.
> My output would look like this.
> Severity CallCount
> -- --
> 1 2
> 2 25
> 3 50
>
> Now, for the month of February, say there were zero(0)
> severity 1 calls, 30 severity 2, and 77 severity 3, I
> want my output to look like this
> Severity CallCount
> -- --
> 1 0
> 2 30
> 3 77
> ....However, my problem is that I do not get a record
> for severity 1 cuz there are no calls for that month.
> My query is below. What am I doing wrong? There is no
> relationship between the two tables. The Severity table
> just stores detail information regarding each of the
> severities such as required response time and repair time
> to fix a problem based on the severity. Please help.
> SELECT
> Severity.Severity,
> Severity.ResponseTime,
> Severity.RepairTime,
> Count(Call.CallNo) As CallCount
> FROM
> Severity
> Left Join Call
> On Severity.Severity = Call.Severity
> WHERE
> Call.DateTimeSubmitted Between '01/01/2004'
> and '01/31/2004'
> AND
> Call.Status <> 'CANCELLED'
> GROUP BY
> Severity.Severity,
> Severity.ResponseTime,
> Severity.RepairTime,
> Order By
> Severity.Severity
> TIA,
> Vic