Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Thursday, March 29, 2012

Concatenate a string problem

Hi to all:

In my package, I have in OLE DB SOURCE a statement:

DECLARE @.CMonth as smalldatetime

SET @.CMonth = '11/1/2006'

select day(@.CMonth)+month(@.CMonth)+year(@.CMonth)as ID_Month

and in OLE DB DESTINATION, I have ID_Month column as a char(10).

I want to be result as concatenated string – 1112006, but I receive 2018 (As a result of calculation)

Can anybody help me? Thank you

DECLARE @.CMonth as smalldatetime

SET @.CMonth = '11/1/2006'

select cast(day(@.CMonth) as varchar(2))+cast(month(@.CMonth) as varchar(2))+cast(year(@.CMonth) as varchar(4)) as ID_Month

|||Thank you very much Attila Soos. It works great!

Tuesday, March 27, 2012

Concat rows into string

I have a simple select statement - select groupname FROM Groups
This returns 30 rows. What I want is return everything as comma
seperated string like "group1, group2, group3..."
But I don't want to use function or cursor. Is there anyway? In on
SQL 2000.
thanksPlease have a look at this example:
http://p2p.wrox.com/topic.asp?TOPIC_ID=57982
Cheers,
Paul Ibison

Concat rows into string

I have a simple select statement - select groupname FROM Groups
This returns 30 rows. What I want is return everything as comma
seperated string like "group1, group2, group3..."
But I don't want to use function or cursor. Is there anyway? In on
SQL 2000.
thanksPlease have a look at this example:
http://p2p.wrox.com/topic.asp?TOPIC_ID=57982
Cheers,
Paul Ibison

Sunday, March 25, 2012

Computer Login using SQL

Is there a SQL statement to get the computers login (not
SQL login)?Check out sp_who, sp_who2, and sp_who3 in the BOL, not in the BOL, and
http://www.planet-source-code.com/URLSEO/vb/scripts/ShowCode!asp/txtCodeId!676/lngWid!5/anyname.htm
respectively.
hth
Eric
"Phil" <anonymous@.discussions.microsoft.com> wrote in message
news:092f01c3b36c$5f539960$a001280a@.phx.gbl...
> Is there a SQL statement to get the computers login (not
> SQL login)?|||What do you mean by computers login?
Rand
This posting is provided "as is" with no warranties and confers no rights.sqlsql

Computer Hang Up when using MDX Query Builder?

hello,
I have some reports using OLAP cube as data sources. When I use mdx
query builder to create any mdx statement as dataset, my computer will hang
up and pop up a window says:
Preparing Query: The query preparation is in process, to cancel, press
CTRL+C for at least half a second.
Even if I press CTRL+C for a long time, my computer still has no
response and hang up forever. I have tried these mdx statement in my SQL
server and they work fine. So this should not be an Analysis Serverices
problem. Would you please tell me how to solve this problem?I've found that if I create a huge data set with the mdx query builder, I
have to leave my computer to it and go get a cup of coffee while it chews
through the data.
Or you could add a few filters to it before starting the query execution, to
make sure the data set it returns is too big. Adding a date filter and make
it default to the last month or date will usually decrease the amount of
data returned.
My pc is running with 2 GB RAM and not a lot of applications in the back
ground. It still uses some time to chew through a data set that finishes
quite quickly in the SQL Server management studio, so I agree with you, it's
a RS issue more than an AS issue. You just have to be carefull about your
statement while using the builer, I guess.
Kaisa M. Lindahl Lervik
"jimmy" <jimmy@.discussions.microsoft.com> wrote in message
news:7375D569-D9C8-4309-8BA6-E46C8582FE32@.microsoft.com...
> hello,
> I have some reports using OLAP cube as data sources. When I use mdx
> query builder to create any mdx statement as dataset, my computer will
> hang
> up and pop up a window says:
> Preparing Query: The query preparation is in process, to cancel, press
> CTRL+C for at least half a second.
> Even if I press CTRL+C for a long time, my computer still has no
> response and hang up forever. I have tried these mdx statement in my SQL
> server and they work fine. So this should not be an Analysis Serverices
> problem. Would you please tell me how to solve this problem?
>|||write more efficient MDX statements?
share your MDX statement when you're having performance problems?
try not to use soo many crossjoins?
-Aaron
Kaisa M. Lindahl Lervik wrote:
> I've found that if I create a huge data set with the mdx query builder, I
> have to leave my computer to it and go get a cup of coffee while it chews
> through the data.
> Or you could add a few filters to it before starting the query execution, to
> make sure the data set it returns is too big. Adding a date filter and make
> it default to the last month or date will usually decrease the amount of
> data returned.
> My pc is running with 2 GB RAM and not a lot of applications in the back
> ground. It still uses some time to chew through a data set that finishes
> quite quickly in the SQL Server management studio, so I agree with you, it's
> a RS issue more than an AS issue. You just have to be carefull about your
> statement while using the builer, I guess.
> Kaisa M. Lindahl Lervik
>
> "jimmy" <jimmy@.discussions.microsoft.com> wrote in message
> news:7375D569-D9C8-4309-8BA6-E46C8582FE32@.microsoft.com...
> > hello,
> >
> > I have some reports using OLAP cube as data sources. When I use mdx
> > query builder to create any mdx statement as dataset, my computer will
> > hang
> > up and pop up a window says:
> >
> > Preparing Query: The query preparation is in process, to cancel, press
> > CTRL+C for at least half a second.
> >
> > Even if I press CTRL+C for a long time, my computer still has no
> > response and hang up forever. I have tried these mdx statement in my SQL
> > server and they work fine. So this should not be an Analysis Serverices
> > problem. Would you please tell me how to solve this problem?
> >
> >|||Hi, Kaisa
Thanks a lot for your suggestions. I have tried a very simple mdx with a
middle size data set. e.g.
SELECT NON EMPTY { } ON COLUMNS,
{ ([Financial Period].[Fiscal].[Fiscal Year].ALLMEMBERS ) } ON ROWS FROM
[myCube]
My computer has a 1GB RAM, not so bad...This query will take about 1
second in my SQL server, however in ES it just hang up for hours and never
get back again, much more than a cup of coffee time.
I will try that on another computer to have a test and I do not think
that will happen too.
Do you think I should remove SQL server or Visual Studio and install
again?Thanks.
"Kaisa M. Lindahl Lervik" wrote:
> I've found that if I create a huge data set with the mdx query builder, I
> have to leave my computer to it and go get a cup of coffee while it chews
> through the data.
> Or you could add a few filters to it before starting the query execution, to
> make sure the data set it returns is too big. Adding a date filter and make
> it default to the last month or date will usually decrease the amount of
> data returned.
> My pc is running with 2 GB RAM and not a lot of applications in the back
> ground. It still uses some time to chew through a data set that finishes
> quite quickly in the SQL Server management studio, so I agree with you, it's
> a RS issue more than an AS issue. You just have to be carefull about your
> statement while using the builer, I guess.
> Kaisa M. Lindahl Lervik
>
> "jimmy" <jimmy@.discussions.microsoft.com> wrote in message
> news:7375D569-D9C8-4309-8BA6-E46C8582FE32@.microsoft.com...
> > hello,
> >
> > I have some reports using OLAP cube as data sources. When I use mdx
> > query builder to create any mdx statement as dataset, my computer will
> > hang
> > up and pop up a window says:
> >
> > Preparing Query: The query preparation is in process, to cancel, press
> > CTRL+C for at least half a second.
> >
> > Even if I press CTRL+C for a long time, my computer still has no
> > response and hang up forever. I have tried these mdx statement in my SQL
> > server and they work fine. So this should not be an Analysis Serverices
> > problem. Would you please tell me how to solve this problem?
> >
> >
>
>|||im not sure that's such a simple MDX statement
do you have granularity to the seconds dimension?
how many members do you have in this dim?
I would do this and see if it's a lot faster:
Select [Financial Period].[Fiscal].[Fiscal Year].MEMBERS on COLUMNS
FROM MyCube
and see if that's a lot faster.
-Aaron
jimmy wrote:
> Hi, Kaisa
> Thanks a lot for your suggestions. I have tried a very simple mdx with a
> middle size data set. e.g.
> SELECT NON EMPTY { } ON COLUMNS,
> { ([Financial Period].[Fiscal].[Fiscal Year].ALLMEMBERS ) } ON ROWS FROM
> [myCube]
> My computer has a 1GB RAM, not so bad...This query will take about 1
> second in my SQL server, however in ES it just hang up for hours and never
> get back again, much more than a cup of coffee time.
> I will try that on another computer to have a test and I do not think
> that will happen too.
> Do you think I should remove SQL server or Visual Studio and install
> again?Thanks.
>
> "Kaisa M. Lindahl Lervik" wrote:
> > I've found that if I create a huge data set with the mdx query builder, I
> > have to leave my computer to it and go get a cup of coffee while it chews
> > through the data.
> > Or you could add a few filters to it before starting the query execution, to
> > make sure the data set it returns is too big. Adding a date filter and make
> > it default to the last month or date will usually decrease the amount of
> > data returned.
> > My pc is running with 2 GB RAM and not a lot of applications in the back
> > ground. It still uses some time to chew through a data set that finishes
> > quite quickly in the SQL Server management studio, so I agree with you, it's
> > a RS issue more than an AS issue. You just have to be carefull about your
> > statement while using the builer, I guess.
> >
> > Kaisa M. Lindahl Lervik
> >
> >
> > "jimmy" <jimmy@.discussions.microsoft.com> wrote in message
> > news:7375D569-D9C8-4309-8BA6-E46C8582FE32@.microsoft.com...
> > > hello,
> > >
> > > I have some reports using OLAP cube as data sources. When I use mdx
> > > query builder to create any mdx statement as dataset, my computer will
> > > hang
> > > up and pop up a window says:
> > >
> > > Preparing Query: The query preparation is in process, to cancel, press
> > > CTRL+C for at least half a second.
> > >
> > > Even if I press CTRL+C for a long time, my computer still has no
> > > response and hang up forever. I have tried these mdx statement in my SQL
> > > server and they work fine. So this should not be an Analysis Serverices
> > > problem. Would you please tell me how to solve this problem?
> > >
> > >
> >
> >
> >

Thursday, March 22, 2012

Computed column

Hi,
I am trying yo return a set or records by using a SELECT statement, the
table contains a column called CreationDate.
I want to add one more column to the resulting dataset (not to the table),
that value of the column will be 1 if the CreationDate is 1 day before the
current time, 0 otherwise.
Any idea how to do it?
thanks first,
Gnicuse a case statement.
SELECT 'return' = case
WHEN datediff > 0 THEN 1
ELSE 0
FROM table|||I tried the statement and it returns
"Incorrect syntax near the keyword 'FROM'."
So it doesn't work, it that a Yukon feature?
Because I am using SQL Server 2000
thanks
"Red2" <sdibello@.gmail.com> wrote in message
news:1142952098.221443.242870@.i39g2000cwa.googlegroups.com...
> use a case statement.
> SELECT 'return' = case
> WHEN datediff > 0 THEN 1
> ELSE 0
> FROM table
>|||Oh I found that I need to add an END keyword at the end the case statement.
It works now.
thanks for your help
Gnic
"Gnic" <gasnic@.gmail.com> wrote in message
news:e4rrd8QTGHA.1868@.TK2MSFTNGP09.phx.gbl...
>I tried the statement and it returns
> "Incorrect syntax near the keyword 'FROM'."
> So it doesn't work, it that a Yukon feature?
> Because I am using SQL Server 2000
> thanks
>
> "Red2" <sdibello@.gmail.com> wrote in message
> news:1142952098.221443.242870@.i39g2000cwa.googlegroups.com...
>sqlsql

Computed column

Hi,
I am trying yo return a set or records by using a SELECT statement, the
table contains a column called CreationDate.
I want to add one more column to the resulting dataset (not to the table),
that value of the column will be 1 if the CreationDate is 1 day before the
current time, 0 otherwise.
Any idea how to do it?
thanks first,
Gnic
use a case statement.
SELECT 'return' = case
WHEN datediff > 0 THEN 1
ELSE 0
FROM table
|||I tried the statement and it returns
"Incorrect syntax near the keyword 'FROM'."
So it doesn't work, it that a Yukon feature?
Because I am using SQL Server 2000
thanks
"Red2" <sdibello@.gmail.com> wrote in message
news:1142952098.221443.242870@.i39g2000cwa.googlegr oups.com...
> use a case statement.
> SELECT 'return' = case
> WHEN datediff > 0 THEN 1
> ELSE 0
> FROM table
>
|||Oh I found that I need to add an END keyword at the end the case statement.
It works now.
thanks for your help
Gnic
"Gnic" <gasnic@.gmail.com> wrote in message
news:e4rrd8QTGHA.1868@.TK2MSFTNGP09.phx.gbl...
>I tried the statement and it returns
> "Incorrect syntax near the keyword 'FROM'."
> So it doesn't work, it that a Yukon feature?
> Because I am using SQL Server 2000
> thanks
>
> "Red2" <sdibello@.gmail.com> wrote in message
> news:1142952098.221443.242870@.i39g2000cwa.googlegr oups.com...
>
sqlsql

Compute By Clause problem in SQL 2000

I am having a problem with this compute by clause

The statement is a simple select

Select col1, col2 from table1
where <where clause>
order by col1
Compute Sum(col2) by col1

I want the display to show details and group totals.

The error message I keep getting is
Server: Msg 410, Level 16, State 2, Line 1
COMPUTE clause #1 'BY' expression #1 is not in the order by list.

I have previously used the compute clause so I know it should work !!

Ay help will be appreciated - Thank you.This is working for pubs - I do not see the difference.

SELECT type, price
FROM titles
ORDER BY type
COMPUTE SUM(price) BY type|||I saw this very same example and did my query and it doesn't work. I don't have the pubs database so I created a titles table and inserted some data and then ran this same query and that too gave me the same error !!!

Originally posted by snail
This is working for pubs - I do not see the difference.

SELECT type, price
FROM titles
ORDER BY type
COMPUTE SUM(price) BY type|||Originally posted by CSC
I saw this very same example and did my query and it doesn't work. I don't have the pubs database so I created a titles table and inserted some data and then ran this same query and that too gave me the same error !!!

I am afraid you have a problem with your sql server - is it microsoft 2000?|||Yes it is Microsoft Sql Server 2000. This is really strange !!

Originally posted by snail
I am afraid you have a problem with your sql server - is it microsoft 2000?

Tuesday, March 20, 2012

Compound IIF Statement

The compound statement:
=Iif(DateDiff("d", Fields!TranDate.Value, Parameters!AgeDate.Value) > 30 &
DateDiff("d", Fields!TranDate.Value, Parameters!AgeDate.Value) < 61,
Fields!Amount.Value, "")
The purpose of the above statement is to print the "Amount.Value" if the #
of days is greater than 30 and less than 61. The problem is that it prints
the value "Amount.Value" and ignores the actual # of days. IE, if the
difference in the dates is 15, "Amount.Value" is printed. Is this syntax
correct? Can you have compound statements using DateDiff?
Thanks,
JohnYou are using & instead of AND. & is appending the two values together
instead of doing a boolean compare.
Oh, you can definitely have compound iif statements but you are not doing
that. A compound iif would be iif(some boolean expression, true value,
iif(blah, blah, blah))
--
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"John Joslin" <JohnJoslin@.discussions.microsoft.com> wrote in message
news:945474CD-1373-43E4-AD35-01DBCF3671FF@.microsoft.com...
> The compound statement:
> =Iif(DateDiff("d", Fields!TranDate.Value, Parameters!AgeDate.Value) > 30 &
> DateDiff("d", Fields!TranDate.Value, Parameters!AgeDate.Value) < 61,
> Fields!Amount.Value, "")
> The purpose of the above statement is to print the "Amount.Value" if the #
> of days is greater than 30 and less than 61. The problem is that it prints
> the value "Amount.Value" and ignores the actual # of days. IE, if the
> difference in the dates is 15, "Amount.Value" is printed. Is this syntax
> correct? Can you have compound statements using DateDiff?
> Thanks,
> John|||Thanks Bruce! It works very nicely now...
"Bruce L-C [MVP]" wrote:
> You are using & instead of AND. & is appending the two values together
> instead of doing a boolean compare.
> Oh, you can definitely have compound iif statements but you are not doing
> that. A compound iif would be iif(some boolean expression, true value,
> iif(blah, blah, blah))
> --
> Bruce Loehle-Conger
> MVP SQL Server Reporting Services
> "John Joslin" <JohnJoslin@.discussions.microsoft.com> wrote in message
> news:945474CD-1373-43E4-AD35-01DBCF3671FF@.microsoft.com...
> > The compound statement:
> >
> > =Iif(DateDiff("d", Fields!TranDate.Value, Parameters!AgeDate.Value) > 30 &
> > DateDiff("d", Fields!TranDate.Value, Parameters!AgeDate.Value) < 61,
> > Fields!Amount.Value, "")
> >
> > The purpose of the above statement is to print the "Amount.Value" if the #
> > of days is greater than 30 and less than 61. The problem is that it prints
> > the value "Amount.Value" and ignores the actual # of days. IE, if the
> > difference in the dates is 15, "Amount.Value" is printed. Is this syntax
> > correct? Can you have compound statements using DateDiff?
> >
> > Thanks,
> >
> > John
>
>

Monday, March 19, 2012

Composite key "NOT IN" query?

I have a table with a composite key formed by the unique combination of columns w, x, y, z

I'm trying to write an INSERT statement along the following lines

INSERT INTO myTable

(SELECT w, x, y, z FROM someTable) t1

WHERE (this is the part I'm stumped on - where the unique combination of w, x, y, z is NOT in myTable already)

Help would be appreciated. Can you use the NOT IN keyword on composite values?

Can you use the NOT IN keyword on composite values?

Yes,but that is expensive.

FromQuery SQL Server Performance Tuning Tips

But If you currently have a query that uses NOT IN, which offers poor performance because the SQL Server optimizer has to use a nested table scan to perform this activity, instead try to use one of the following options instead, all of which offer better performance:

Use EXISTS or NOT EXISTS|||

INSERT INTO MyTable

SELECT t1.w,t1.x,t1.y,t1.z

FROM someTable t1

LEFT JOIN MyTable t2 ON t1.w=t2.w and t1.x=t2.x and t1.y=t2.y and t1.z=t2.z

WHERE t2.w IS NULL

This should also work:

INSERT INTO MyTable

SELECT w,x,y,z

FROM someTable

EXCEPT

SELECT w,x,y,z

FROM MyTable

Sunday, March 11, 2012

Complicated Update Statement

Hi All,

I need to write one complicated update statement and I'm looking at
maybe finding a simpler way to do it.

I have 2 tables:

1.Photo Table
PhotoID FileName
1 111.jpg
1 111_01.jpg
2 222.jpg
2 222_01.jpg
2 222_02.jpg
3 333.jpg

2.PhotoReport Table
PhotoID FileName1 FileName2 FileName3....FileName12
1 111.jpg 111_01.jpg NULL NULL
2 222.jpg 222_01.jpg 222_02.jpg
..
..
..
I need to update PhotoReport Table to look like an example above. I've
started writing my code and it looks very hedeous with multiple nested
cursors.
So if someone has a sample of a code to accomplish this, please pretty
please send it my way. I appreciate it in advance.

Thank you,
Narine"Narine" <narine.kostandyan@.prurealty.com> wrote in message
news:5628948a.0406111054.2e24cb1b@.posting.google.c om...
> Hi All,
> I need to write one complicated update statement and I'm looking at
> maybe finding a simpler way to do it.
> I have 2 tables:
> 1.Photo Table
> PhotoID FileName
> 1 111.jpg
> 1 111_01.jpg
> 2 222.jpg
> 2 222_01.jpg
> 2 222_02.jpg
> 3 333.jpg
> 2.PhotoReport Table
> PhotoID FileName1 FileName2 FileName3....FileName12
> 1 111.jpg 111_01.jpg NULL NULL
> 2 222.jpg 222_01.jpg 222_02.jpg
> .
> .
> .
> I need to update PhotoReport Table to look like an example above. I've
> started writing my code and it looks very hedeous with multiple nested
> cursors.
> So if someone has a sample of a code to accomplish this, please pretty
> please send it my way. I appreciate it in advance.
> Thank you,
> Narine

You're looking for a crosstab query:

http://www.aspfaq.com/show.asp?id=2462

Simon|||[posted and mailed, please reply in news]

Narine (narine.kostandyan@.prurealty.com) writes:
> I need to write one complicated update statement and I'm looking at
> maybe finding a simpler way to do it.
> I have 2 tables:
> 1.Photo Table
> PhotoID FileName
> 1 111.jpg
> 1 111_01.jpg
> 2 222.jpg
> 2 222_01.jpg
> 2 222_02.jpg
> 3 333.jpg
> 2.PhotoReport Table
> PhotoID FileName1 FileName2 FileName3....FileName12
> 1 111.jpg 111_01.jpg NULL NULL
> 2 222.jpg 222_01.jpg 222_02.jpg
> .
> .
> .
> I need to update PhotoReport Table to look like an example above. I've
> started writing my code and it looks very hedeous with multiple nested
> cursors.
> So if someone has a sample of a code to accomplish this, please pretty
> please send it my way. I appreciate it in advance.

Cursors? You don't need cursors for this! But you here you get a
12-way self-join. Here I use a temp table, to make this a little
less verbose and more efficient:

CREATE TABLE photos (id int NOT NULL,
filename varchar(23) NOT NULL,
CONSTRAINT pk_photos PRIMARY KEY (id, filename))
go
CREATE TABLE photoreport (id int NOT NULL,
filename1 varchar(23) NOT NULL,
filename2 varchar(23) NULL,
filename3 varchar(23) NULL,
filename4 varchar(23) NULL,
filename5 varchar(23) NULL,
filename6 varchar(23) NULL,
filename7 varchar(23) NULL,
filename8 varchar(23) NULL,
filename9 varchar(23) NULL,
filename10 varchar(23) NULL,
filename11 varchar(23) NULL,
filename12 varchar(23) NULL DEFAULT 'test',
CONSTRAINT pk_report PRIMARY KEY(id))
go
INSERT photos (id, filename) values (1, '111.jpg')
INSERT photos (id, filename) values (1, '111_01.jpg')
INSERT photos (id, filename) values (2, '222.jpg')
INSERT photos (id, filename) values (2, '222_01.jpg')
INSERT photos (id, filename) values (2, '222_02.jpg')
INSERT photos (id, filename) values (3, '333.jpg')
INSERT photos (id, filename) values (3, '333_01.jpg')
INSERT photos (id, filename) values (3, '333_03.jpg')
go
INSERT photoreport (id, filename1)
SELECT id, MIN(filename)
FROM photos
GROUP BY id
go
SELECT id, filename,
rowno = (SELECT COUNT(*)
FROM photos p2
WHERE p1.id = p2.id
AND p1.filename >= p2.filename)
INTO #temp
FROM photos p1
ORDER BY id, filename

UPDATE photoreport
SET filename1 = t1.filename,
filename2 = t2.filename,
filename3 = t3.filename,
filename4 = t4.filename,
filename5 = t5.filename,
filename6 = t6.filename,
filename7 = t7.filename,
filename8 = t8.filename,
filename9 = t9.filename,
filename10 = t10.filename,
filename11 = t11.filename,
filename12 = t12.filename
FROM photoreport r
JOIN #temp t1 ON t1.id = r.id
AND t1.rowno = 1
LEFT JOIN #temp t2 ON t2.id = r.id
AND t2.rowno = 2
LEFT JOIN #temp t3 ON t3.id = r.id
AND t3.rowno = 3
LEFT JOIN #temp t4 ON t4.id = r.id
AND t4.rowno = 4
LEFT JOIN #temp t5 ON t5.id = r.id
AND t5.rowno = 5
LEFT JOIN #temp t6 ON t6.id = r.id
AND t6.rowno = 6
LEFT JOIN #temp t7 ON t7.id = r.id
AND t7.rowno = 7
LEFT JOIN #temp t8 ON t8.id = r.id
AND t8.rowno = 8
LEFT JOIN #temp t9 ON t9.id = r.id
AND t9.rowno = 9
LEFT JOIN #temp t10 ON t10.id = r.id
AND t10.rowno = 10
LEFT JOIN #temp t11 ON t11.id = r.id
AND t11.rowno = 11
LEFT JOIN #temp t12 ON t12.id = r.id
AND t12.rowno = 122

SELECT * FROM photoreport
go
DROP TABLE #temp, photoreport, photos
go

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||
Simon and Erland,

Thank you very much for helping me out here.
Erland's example worked for me because in my case I had to generate a
rownum column to be able to use the Case statement.

Thanks a million,
Narine

*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!

complicated update (for me)

hello everyone,
just having trouble with an update statement. so i started off with a
table like so:
create table foo (
id uniqueidentifier not null primary key nonclustered,
name varchar(50) not null,
type int not null,
datecreated datetime not null default getdate(),
constraint foo1 unique (name)
)
go
then i added a new column, like so:
alter table foo add column rank int null
go
and here's where the tricky update comes in. my goal is to populate
this new "rank" column with incremental values for each distinct "type"
value.
for example, i the original table looks like so:
select name, type from foo
go
name type
-- --
john 1
jane 1
jim 1
jake 2
jeff 2
kyle 2
keli 2
kim 2
i would want the update statement to populate the table so that AFTER
the update, it looks like so:
select name, type, rank from foo
name type rank
-- -- --
john 1 1
jane 1 2
jim 1 3
jake 2 1
jeff 2 2
kyle 2 3
keli 2 4
kim 2 5
it's important to note that the original "rank" really doesn't matter,
it is just something that needs to be kept track of moving forward, so
i don't even particularly have to rank them alphabetically, or any
other way. just need an update statement that can put in incremental
values, but that sort of "resets" the incrementation for each changing
value of another field.
if that's possible.
thanks in advance for any help!
jasonYou have a few problems with this. First, a uniqueidentifier cannot be
a relational key, so this is not a table by definition. Where does it
occur in the reality of the data model? Next, Rows are not records;
fields are not columns; tables are not files. Totally differerent
concepts. You are building a sequential file in SQL
DEFAULT comes after the data type in STANDARD SQL, and you can use
CURRENT_TIMESTAMP instead of the proprietary getdate(). But you should
not put audit trail information in the table (ask your accountant about
proper procedures).
There is no sequential access or ordering in an RDBMS, so "first",
"next" and "last" are totally meaningless. So what are you using to
assign the rank values? The data model should have some rule so you
can validate the data.
Granted this is a sample table, but all of the column names are
incomplete (type of what? Name of what? Etc.) Your sample design
should look more like this:
CREATE TABLE NewFoo
(foo_name VARCHAR(50) NOT NULL PRIMARY KEY,
foo_type INTEGER NOT NULL,
bar_rank INTEGER NOT NULL,
UNIQUE (foo_type, bar_rank)); -- is this the PK?
Now, let's kill the old one and get things into an RDBMS:
INSERT INTO NewFoo (foo_name, foo_type, bar_rank)
SELECT name, type,
(SELECT COUNT(F1.*)
FROM Foo AS F1
WHERE F1.type = Foo.type
AND F1.name = Foo.name)
FROM Foo;
Then drop Foo and rename NewFoo.|||> First, a uniqueidentifier cannot be a relational key, so this
> is not a table by definition. Where does it occur in the
> reality of the data model?
i call bs on this one, CELKO. a uniqueidentifier is a perfectly valid
artificial key for any record. what makes you think it can't be a
relational key?

> But you should not put audit trail information in the table
i call bs on this one too, i'm afraid. row-level auditing is a
perfectly valid practice for a number of reasons.
as for the rest, yeah, i was lazy, i didn't actually try the create
table statement before posting :) and i'll try to be more descriptive
in future examples.
as for the rank, it's definitely not an attempt to make the table a
sequential file, so you guessed wrong there i'm afraid. i use clustered
indexes if order is important for something, which has specific,
uncommon purposes in my opinion.
the rank is a meaningful value that a subscriber application needs to
know. you can think of it like your standing in a contest, you're
either in first, second, third, etc. place. the rank can't actually be
determined by any values in the database, it is determined by the
providers of the data, and we just store the rank. it's meaningful, not
physically sequential, etc.
and lastly, regarding the insert statement: THANK YOU. exactly what i
was looking for. i look forward to trying it out when i get back to the
office tomorrow.
thankful as always,
jason|||>> call bs on this one, CELKO. a uniqueidentifier is a perfectly valid artificial
key for any record [sic]. what makes you think it can't be a relational key? <<
The very definition of a relationall key, the stuff Dr. Codd wrote and
basic data model concepts. A relational key is subset of the
attributes of an entity that is unique. A uniqueidentifier is derived
from physical storage and has nothing whatsoever to do with the entity.
Newbies who do not know that a row (logical construct) is nothing like
a record (physical storage) constantly make this mistake and build file
systems in SQL.
An artificial key has to have validation and verification rules, and a
uniqueidentifier does not.
That is fine, but putting the audit trail into the table that is being
audited is not a proper accounting practice. The changes need to be
caught outside of the table. Talk to the accounting department or the
SOX guy for your company. This is like letting developers do their own
QA.|||assuming (name, type) is unique
update foo set rank = (select count(*) from foo f1 where f1.type =
foo.type and f1.name<foo.name)+1
if (name, type) is NOT unique, it it still doable but more complex|||> A uniqueidentifier is derived from physical storage
well, I guess whoever says this at a job interview is less likely to
get hired ;)|||> A relational key is subset of the
> attributes of an entity that is unique.
actually, if i'm reading you correctly, that's a called NATURAL key.
relational keys do not have the necessary condition of being natural
elements of an entity. the only necessary condition of a relational key
is that it be a column or columns whose values are gauranteed to be
unique across all occurrences in a given table. that's it.
by this definition, a relational key can be natural OR artificial. what
you're describing is a natural relational key, and good for you, that's
totally fine. and so are artificial relational keys.

> An artificial key has to have validation and verification rules, and a
> uniqueidentifier does not.
the only "validation and verification" rule required to act as a
relational key is that it be UNIQUE. and uniqueidentifiers, when
properly used, are certainly that.
i presume that you would have just as many objections about using an
identity integer as a relational key? if that's true, then you're
grossly misrepresenting your argument. you're not arguing the
definition of a relational key, you're arguing the validity of
artificial versus natural keys AS relational keys. totally different
argument.

> That is fine, but putting the audit trail into the table that is being
> audited is not a proper accounting practice.
i don't see your logic here. what is the difference between attaching
such a column to the entity it is auditing and putting it in another
table, and relating it to the entity it is auditing? the only
difference i can think of is that you could apply different user
permissions to each table. that's fine and well, but there are plenty
of other places to handle security, and other considerations, such as
performance.|||this worked like a charm, thank you very much!
jason|||yeah, i wasn't sure where that was coming from either. aren't they
derived from like a bunch of crazy variables? datetime, cpu serial
number, mac address, your mother's maiden name, the position of the
every valence electron in your body ...|||>> what is the difference between attaching such a column to the entity it i
s auditing and putting it in another table, and relating it to the entity it
is auditing? <<
You do not have to put the audit information in the schema at all. It
can be in an external file system or other RDBMS.
Separation is a basic accounting principle, like double entry
bookkeeping. For example, when I submit an article to a publisher, I
send the editor one copy of the invoice and another copy to Accounts
Payable. The A/P clerk has to match both copies of the invoice before
they issue a check to me.
My editor deletes their copies of my invoice. The A/P clerk now has an
invoice without a mate at the end of the payment cycle, so they know to
start calling people.
The A/P department deletes their copies of my invoice. The editor now
has an invoice which was no paid at the end of the payment cycle, so
they know to call the A/P department.
Both editor and A/P delete their copies of my invoice. Accounting sees
a missing invoice number at the end of the payment cycle, because they
designed an invoice number that can be validated and verified rather
than a meaningless, hardware generated number. Accounting makes life
hell for everyone until they can trace that missing invoice number.
.

Complicated SELECT Problem

I'm having some trouble coming up with the correct select statement.
Lets say I have the following two tables:

------ ------
Orders OrderItem
------ ------
PK OrderID (int) PK OrderItemID (int)
OrderDate (datetime) FK OrderID (int)
CustomerName (nvarchar) Priority (int)

My search would basically return a list of all the orders placed within
the last week. The select statement would include the entire contents
of the Orders table. The tricky part is that I also need to return the
number of items within each order that have a priority of 1 (so they
can be displayed more prominently).

The first part of the select statement is easy enough, but I'm stuck on
the count part. I'd appreciate any help. Here's what I have so far:

SELECT
Orders.OrderID,
Orders.OrderDate,
Orders.CustomerName
FROM
Orders
WHERE
DATEDIFF(dd, Orders.OrderDate, GetDate()) < 7

--
JasonMaybe I am missing something. I didn't understand how priority of 1
mattered. The field wasn't in your database structure.

SELECT
Orders.OrderID,
Orders.OrderDate,
Orders.CustomerName,
(select count(orderid) from orderitem where
orders.orderid=orderitem.orderid) as Count
FROM Orders
WHERE DATEDIFF(dd, Orders.OrderDate, GetDate()) < 7

Jason wrote:
> I'm having some trouble coming up with the correct select statement.
> Lets say I have the following two tables:
> ------ ------
> Orders OrderItem
> ------ ------
> PK OrderID (int) PK OrderItemID (int)
> OrderDate (datetime) FK OrderID (int)
> CustomerName (nvarchar) Priority (int)
> My search would basically return a list of all the orders placed
within
> the last week. The select statement would include the entire
contents
> of the Orders table. The tricky part is that I also need to return
the
> number of items within each order that have a priority of 1 (so they
> can be displayed more prominently).
> The first part of the select statement is easy enough, but I'm stuck
on
> the count part. I'd appreciate any help. Here's what I have so far:
> SELECT
> Orders.OrderID,
> Orders.OrderDate,
> Orders.CustomerName
> FROM
> Orders
> WHERE
> DATEDIFF(dd, Orders.OrderDate, GetDate()) < 7
> --
> Jason|||Thanks. That should work just fine. I was unaware that you could
include a select statement inside another select like that. You learn
something new every day.

--
Jason|||AS400 Guru (hazen@.candid.com) writes:
> Maybe I am missing something. I didn't understand how priority of 1
> mattered. The field wasn't in your database structure.

It is in OrderItem.

> SELECT
> Orders.OrderID,
> Orders.OrderDate,
> Orders.CustomerName,
> (select count(orderid) from orderitem where
> orders.orderid=orderitem.orderid) as Count
> FROM Orders
> WHERE DATEDIFF(dd, Orders.OrderDate, GetDate()) < 7

This is likely to perform better:

SELECT o.OrderID, o.OrderDate, o.CustomerName, coalesce(oi.cnt, 0)
FROM Orders o
LEFT JOIN (SELECT OrderId, cnt = COUNT(*)
FROM OrderItem
WHERE Priority = 1
GROUP BY OrderId) oi ON o.OrderID = oi.OrderID
WHERE DATEDIFF(dd, Orders.OrderDate, GetDate()) < 7

It's always a good idea to benchmark different solutions. But my experience
is that a derived table gives better performance that sub-selects in the
SELECT list. The latter are usally computed for each row, whereas the
derived table permits the optimizer to do all at once.

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

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

Thursday, March 8, 2012

Complicate select statement (I think)

HI all,
I want to create a selectect statement with a computed colulm where the
computed column takes into account the result of the computed colum of the
prevuous row
psudo code: if the total-cap>total then cap else total-(previous computed)
eg table and rows
total cap
13000 5000
13000 10000
13000 100000
so my view or result would be
total cap computed
13000 5000 5000
13000 10000 8000
13000 100000 0
THis will be for a claims database where each row represents an loss risk
layer
so that row 1 would be the excess, and the computed column would shou
howmuch of the total claim is within excess.
The next row is the next layer stoppper which would show how much of the
claim falss within that layer, taking into acount the result of any layer
before it, ans so on
So each layer takes off a bit of the claims untill the claim total is
finnished. Basically apportioning the claim between the different layers
I dont have any real data or ddl, I'm still trying to make sure if this can
be achieved
You help is appreciated
Thanks
RObertRobert Bravery wrote:
> HI all,
> I want to create a selectect statement with a computed colulm where the
> computed column takes into account the result of the computed colum of the
> prevuous row
> psudo code: if the total-cap>total then cap else total-(previous computed)
> eg table and rows
> total cap
> 13000 5000
> 13000 10000
> 13000 100000
> so my view or result would be
> total cap computed
> 13000 5000 5000
> 13000 10000 8000
> 13000 100000 0
> THis will be for a claims database where each row represents an loss risk
> layer
> so that row 1 would be the excess, and the computed column would shou
> howmuch of the total claim is within excess.
> The next row is the next layer stoppper which would show how much of the
> claim falss within that layer, taking into acount the result of any layer
> before it, ans so on
> So each layer takes off a bit of the claims untill the claim total is
> finnished. Basically apportioning the claim between the different layers
> I dont have any real data or ddl, I'm still trying to make sure if this ca
n
> be achieved
> You help is appreciated
> Thanks
> RObert
What is/are the key(s) of your table and what determines which row is
the current, previous and next layer? In your example it seems that the
only way to fix the order is based on CAP. Is the CAP column really
unique? If not, then apparently there isn't a unique order. Please post
DDL (CREATE TABLE with keys and constraints) so that we don't have to
guess.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Robert
Why can't you do that on the client side?
create table #test
(
[id] int not null primary key,
total int,
cap int
)
insert into #test values (1,13000,5000)
insert into #test values (2,13000,10000)
insert into #test values (3,13000,100000)
SELECT *,CASE WHEN r>total THEN cap END
FROM
(
SELECT *,total-cap as r
FROM #test
) AS Der

> psudo code: if the total-cap>total then cap else total-(previous computed)
13000-5000 >1300
Don't uderstand your requirements
"Robert Bravery" <me@.u.com> wrote in message
news:uSIar6VLGHA.3936@.TK2MSFTNGP10.phx.gbl...
> HI all,
> I want to create a selectect statement with a computed colulm where the
> computed column takes into account the result of the computed colum of the
> prevuous row
> psudo code: if the total-cap>total then cap else total-(previous computed)
> eg table and rows
> total cap
> 13000 5000
> 13000 10000
> 13000 100000
> so my view or result would be
> total cap computed
> 13000 5000 5000
> 13000 10000 8000
> 13000 100000 0
> THis will be for a claims database where each row represents an loss risk
> layer
> so that row 1 would be the excess, and the computed column would shou
> howmuch of the total claim is within excess.
> The next row is the next layer stoppper which would show how much of the
> claim falss within that layer, taking into acount the result of any layer
> before it, ans so on
> So each layer takes off a bit of the claims untill the claim total is
> finnished. Basically apportioning the claim between the different layers
> I dont have any real data or ddl, I'm still trying to make sure if this
> can
> be achieved
> You help is appreciated
> Thanks
> RObert
>
>|||>> I want to create a SELECT statement with a computed column where the com
puted column takes into account the result of the computed column of the pre
vious row <<
Somebody was aasleep in RDBMS 101! Let's get back to the basics of an
RDBMS. Rows are not records; fields are not columns; tables are not
files; there is no sequential access or ordering in an RDBMS, so
"first", "next" and "last" are totally meaningless. If you want an
ordering, then you need to havs a column that defines that ordering.
You must use an ORDER BY clause on a cursor -- the keys have nothing
whatsoever to do with the display in the front end.
Google up my articles on LIFO and FIFO in SQL at www.dbazine.com. I
think this is what you are after.

complex sql statement, need help

i have a complex sql statement and i think that my structure looks good but apparently not because i keep getting the same error, i was wondering if anyone knew how to correct this problem.

SELECT A.*, B.Name, C.SIName, D.IID,

(Select [LastName] , [FirstName]
FROM E INNER JOIN F ON E.SID =
F.SID , A
WHERE F.Emp='Service' AND E.Lead=1 AND E.ID=[A].[D])
AS Service,

(Select [LastName] , [FirstName]
FROM E INNER JOIN F ON E.SID =
F.SID ,A
WHERE F.Emp='Industry' AND E.Lead=1 AND E.ID=[A].[D])
AS Industry

FROM A , B, C
WHERE (1=1) AND B.SID = C.SID AND A.ID = B.ID

i always get this error: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

does anyone know how to fix this query?Whats this syntax?

FROM E INNER JOIN F ON E.SID =
F.SID , A|||im not entirely sure, im in the process of converting this from access to sql server. i would assume that they are going ahead and assigning the table from which they will be calling on later. i usually dont use the inner join method myself, i will just type what fields i want, then the tables and then the criteria, so im guessing its along the same lines by calling table A and then specifying criteria on the next line
AND E.ID=[A].[D])|||You are getting the error because the subqueries in your select clause return more than one value (LastName and FirstName), and you are trying to assign the results to a single field in your result set (Service).

You can probably avoid the error by concatenating the two values into one:
[LastName] + ' ' + [FirstName]

but this is not a good way to write a sql statement. There are a lot of problems with the code you posted. We can probably give you some help cleaning it up, but you will need to tell us a bit more about what you want to do, and post a description of the tables and their columns.|||Are the tables really called A, B, C?

Can you post the DDL for these tables?

Do you know what the expected result is suppose to be?

I'm guessing they're trying to coorelate to table A for the names...I think I'd make it just part of the join...with a derived table

Alos you should start using the JOIN syntax...it'll be easier for you in the long run

(My Own Opinion)

MOO|||thanks for the info guys, i think i got it fixed, i used blindmans suggestion and it worked. also ill keep your advice in mind brett|||only problem i have now, is it returns each record 15 times|||This is just a guess, and it would really help if we had the DDL for tables A,B,C,E and F (are the tables really called this?) along with some sample data...

But here's a shot

SELECT A.*
, B.Name
, C.SIName
, D.IID
, N1.*
, N2.*
FROM B
INNER JOIN C ON B.ID = C.ID
INNER JOIN A ON B.ID = A.ID
INNER JOIN ( SELECT [LastName] , [FirstName] FROM E
INNER JOIN F ON E.SID = F.SID
WHERE F.Emp='Service' AND E.Lead=1) AS N1
ON N1.ID=A.D
INNER JOIN ( SELECT [LastName] , [FirstName] FROM E
INNER JOIN F ON E.SID = F.SID
WHERE F.Emp='Industry' AND E.Lead=1) AS N2
ON N2.ID=A.D|||You can avoid the duplicated records by using the SELECT DISTINCT syntax, but this and the other suggestion I gave you are really just band-aid solutions for more serious problems.
For instance, your subqueries appear to use cartesian joins to tables that are not reference in the select list or the criteria, and your subqueries in SELECT clauses are not a good idea to begin with. They should be dropped in favor of direct joins or moved to the FROM clause.|||yea i know it would help, but i got it figured out now. i dont have a lot of experience with converting from access to sql and i assumed that a lot of complex changes were neccessary when come to find out, there was really only a small change to convert it. the code i showed you guys obviously included my f'ed up alterations. but the only problem was the &'s from access had to be switched to +'s in sql. so sorry for taking up your time guys.

complex sql statement

I need to get multiple values for each row in a database, then do a calculation and insert the calculation and the accountnumber related to the calculation the data, into a different column. I get an error trying it this way...there is no real identifier, it is jsut something that needs to get done per row...any ideas on how I can accomplish this?

Declare @.NetCommissiondecimal

Declare @.AccountNumbervarchar(50)

Set

@.NetCommission=(select(CommissionRebate* Quantity)

from

Account A

Join

Trades Ton A.AccountNumber= T.AccountNumber)

Set

@.AccountNumber=(select A.AccountNumber

from

cmsAccount A

Join

Trades Ton A.AccountNumber= T.AccountNumber)

Insert

into Transaction

(

Payee

,

Deposit

,

AccountNumber

)

Values

(

'Account Credit'

,

@.NetCommission

,

@.AccountNumber

)

Hi

Insert

intoTransaction

(

Payee

........

Transaction is the key word,you have to choose another table name.

|||Or always embed such object names in [] or "" to avoid "syntax error":

Insert
into [Transaction]

(

Payee...|||

Even with the table name changed I am still getting a subquery error

Subquery returned more than 1 value.

All I really want to do is run a calculation on ech row in the database...any ideas?

Declare @.NetCommissiondecimal

Declare @.AccountNumbervarchar(50)

Set

@.NetCommission=(

select

(CommissionRebate* Quantity)

from

cmsAccount A

Join

cmsTrades Ton A.AccountNumber= T.AccountNumber)

Set

@.AccountNumber=(select A.AccountNumber

from

cmsAccount A

Join

cmsTrades Ton A.AccountNumber= T.AccountNumber)

Insert

into TradeTransaction

(

Payee

,

Deposit

,

AccountNumber

)

Values

(

'Account Credit'

,

@.NetCommission

,

@.AccountNumber

)

Go

|||Obviously the error indicates?that?some?subquery?returns?more?than?1?value?while?you're?trying?to?assign?the?returned?values?to?a?single?variable.?This?is?a?bad?logic?as?there?is?no?array?in?T-SQL.?So?my?suggestion?would?be?to?use?some?aggregation?funciton?or?TOP?keyword?to?restrict?the?subquery?to?return?only?1?value, for example:

Set @.NetCommission =
(select top 1 (CommissionRebate * Quantity)
from cmsAccount A Join
cmsTrades T on A.AccountNumber = T.AccountNumber)

Or:

Set @.NetCommission =
(select max(CommissionRebate * Quantity)
from cmsAccount A Join
cmsTrades T on A.AccountNumber = T.AccountNumber)|||

This gets me the two values I need, but I then need to insert these two values into a different table... how would I go about doing this?

Select

sum(A.CommissionRebate* T.Quantity)As NetCommission, T.AccountNumber

from

cmsTrades T

Join

cmsAccount Aon A.AccountNumber= T.AccountNumber

where

T.TradeDate='11/13/2006'

GROUP

BY T.AccountNumber

|||

Ok this one works but it only inserts the first row and runs successfully, but does not go on to insert the other rows...

Declare

@.NetCommissiondecimal

Declare

@.AccountNumberVarchar(50)

Select

@.NetCommission=Sum(A.CommissionRebate* T.Quantity), @.AccountNumber= T.AccountNumber

from

cmsTrades T

Join

cmsAccount Aon A.AccountNumber= T.AccountNumber

where

T.TradeDate='11/13/2006'

GROUP

BY T.AccountNumber

Insert

into appTransaction

(

Payee

,

Payment

,

AccountNumber

)

Values

(

'Client Credit'

,

@.NetCommission

,

@.AccountNumber

)

|||If you want to insert multiple rows you need to use Cursor to skip through the rows to be inserted, or store the rows in a temple table so that you can?fetch rows from it?into?some?table?in?a?single?insert?statement.|||

I did this with the cursor idea, worked for a second and now I am getting this message: Error converting data type varchar to decimal.

DECLARE

appCursorCursor

For

Select

T.AccountNumber,sum(CommissionRebate)/count(*)*sum(Quantity)as NetCommission

from

cmsTrades T

Join

cmsCalcs con c.AccountNumber= T.AccountNumber

where

T.TradeDate=CAST(YEAR(getdate()) as varchar) + RIGHT('00'+CAST(MONTH(getdate()) as varchar), 2) + RIGHT('00'+CAST(DAY(getdate())-1 as varchar), 2)

and

c

.Month= 11

GROUP

BY T.AccountNumber

Open

appCursor

Declare

@.NetCommissiondecimal, @.AccountNumberVarchar(50)

Fetch

Nextfrom appCursorInto @.NetCommission, @.AccountNumber

While

(@.@.Fetch_Status<>-1)

Begin

If

(@.@.Fetch_Status<>-2)

Insert

into appTransaction

(

Payee

,

Payment

,

AccountNumber

)

Values

(

'Client Credit'

,

@.NetCommission

,

@.AccountNumber

)

Fetch

Nextfrom appCursorInto @.NetCommission, @.AccountNumber

End

Close

appCursor

DEALLOCATE

appCursor

Go

|||I found this:

DECLARE
appCursor Cursor For
Select
T.AccountNumber, sum(CommissionRebate) / count(*) * sum(Quantity) as NetCommission
from
cmsTrades T
.....
Fetch Next from appCursor Into @.NetCommission, @.AccountNumber

Shouldn't this be?Fetch Next from appCursor Into @.AccountNumber, @.NetCommission? The same order as the returned fields in the select query?|||

Forget the cursor. You want to stay away from those as much as possible. Keep with set-based logic; it's the SQL way! :-)

Use this sort of approach instead:

INSERT INTO TradeTransaction
(
Payee,
Deposit,
AccountNumber
)
SELECT
'Account Credit',
CommissionRebate * Quantity,
A.AccountNumber
FROM
cmsAccount A
INNER JOIN
cmsTrades T on A.AccountNumber = T.AccountNumber


|||that works great, would there be an easy way to sum up the inserts by AccountNumber so instead of 36 inserts for one accountnumber I would have just 1 for each accountnumber for that day?|||

Yes, you might try this:


INSERT INTO TradeTransaction
(
Payee,
Deposit,
AccountNumber
)
SELECT
'Account Credit',
SUM(CommissionRebate * Quantity),
A.AccountNumber
FROM
cmsAccount A
INNER JOIN
cmsTrades T on A.AccountNumber = T.AccountNumber
GROUP BY
A.AccountNumber

|||That did the trick perfectly...thank you!

Complex SQL select statement that works but...

I have a pretty complex SQL statement that looks like this:

SELECT aspnet_Employers.active, aspnet_Employers.accountexecutiveusername, aspnet_Employers.created, aspnet_Employers.Title AS Contact,
SUM(aspnet_Employers.EmployeeCount) AS [# Emps], COUNT(aspnet_Signups.account) AS [# Email Addresses], COUNT(aspnet_ContactMe.username)
AS [# Contact Me], COUNT(aspnet_AppsSubmitted.account) AS [# Apply Now]
FROM aspnet_Employers LEFT OUTER JOIN
aspnet_AppsSubmitted ON aspnet_Employers.UserName = aspnet_AppsSubmitted.account LEFT OUTER JOIN
aspnet_ContactMe ON aspnet_Employers.UserName = aspnet_ContactMe.username LEFT OUTER JOIN
aspnet_Signups ON aspnet_Employers.UserName = aspnet_Signups.account
GROUP BY aspnet_Employers.accountexecutiveusername, aspnet_Employers.created, aspnet_Employers.Title, aspnet_Employers.active

It does work the way i want it, but the problem is, on my Gridview when i change the Employers accounts "Active" status either way, it changes the username field from the username of the account, to "null".

Why does it do this?

What would i change to prevent this from happening?

Thanks!

Maybe it is related to Page.IsPostBack?|||Sorry, i should have mentioned this. This is on my aspx page, not in the code behind file.|||

Nevermind, i figured it out.

I was missing username boundfield for my update statement. When it's missing from the <fields> section, but it's in the update statement, it makes it null. Makes sense. Now i know.

Thanks

Wednesday, March 7, 2012

Complex SELECT Statement Help

Hi All,

My sql is a little rusty, i ve been trying to do few things but still no luck. I m trying to query some data in one column based on certain . Here is my puzzle:

I have 7 tables: categories, characteristics, configs, rm_cat, rm_chars, rm_conf and rooms.

And here are the details on these tables:

- categories: {cat_id, cat_name}

- characteristics: {char_id, char}

- configs: {conf_id, conf}

- rm_cat: {room_id, cat_id}

- rm_chars: { room_id, char_id}

- rm_conf: {room_id, conf_id}

- room: {room_id. room_name}

I m trying to select a "room_name" based on a certain cat_id, char_id and conf_id and i don't know how to do this.

Sincerely,

Try this:

select room_name

from room

join rm_conf

on room.[room_id]= rm_conf.[room_id]

join configs

on rm_conf.[conf_id]= configs.[conf_id]

join rm_cat

on room.[room_id]= rm_cat.[room_id]

join rm_chars

on room.[room_id]= rm_chars.[room_id]

join categories

on categories.[cat_id]= rm_cat.[cat_id]

join characteristics

on rm_chars.[char_id]= charateristics.[char_id]

where categories.[cat_id]= @.Cat_ID

and characteristics.[char_id]= @.Char_ID

and configs.[conf_id]= @.Conf_ID

|||

Thanks mpateson ...

Could you please tell me why am i getting this error : "ORA - 01722: invalid number" when i try to apply this select statement in my gridview

<asp:GridViewID="GridView1"runat="server"AllowPaging="True"AllowSorting="True"

DataSourceID="search_result">

</asp:GridView>

<asp:SqlDataSourceID="search_result"runat="server"ConnectionString="<%$ ConnectionStrings:ConnectionStringR25 %>"

ProviderName="<%$ ConnectionStrings:ConnectionStringR25.ProviderName %>"SelectCommand="SELECT R25.ROOMS.ROOM_SHORT FROM R25.ROOMS INNER JOIN R25.RM_CONF ON R25.ROOMS.ROOM_ID = R25.RM_CONF.ROOM_ID INNER JOIN R25.CONFIGS ON R25.RM_CONF.CONF_ID = R25.CONFIGS.CONF_ID INNER JOIN R25.RM_CAT ON R25.ROOMS.ROOM_ID = R25.RM_CAT.ROOM_ID INNER JOIN R25.RM_CHARS ON R25.ROOMS.ROOM_ID = R25.RM_CHARS.ROOM_ID INNER JOIN R25.CATEGORIES ON R25.CATEGORIES.CAT_ID = R25.RM_CAT.CAT_ID INNER JOIN R25.CHARACTERISTICS ON R25.RM_CHARS.CHAR_ID = R25.CHARACTERISTICS.CHAR_ID WHERE (R25.CATEGORIES.CAT_ID = :CAT_ID) AND (R25.CHARACTERISTICS.CHAR_ID = :CHAR_ID) AND (R25.CONFIGS.CONF_ID = :CONF_ID)">

<SelectParameters>

<asp:ControlParameterControlID="RadioButtonList1"DefaultValue="NULL"Name="CAT_ID"

PropertyName="SelectedValue"/>

<asp:ControlParameterControlID="CheckBoxList1"DefaultValue="NULL"Name="CHAR_ID"

PropertyName="SelectedValue"/>

<asp:ControlParameterControlID="DropDownList1"DefaultValue="NULL"Name="CONF_ID"

PropertyName="SelectedValue"/>

</SelectParameters>

</asp:SqlDataSource>

|||

I found this on google.

ORA-01722:invalid numberCause:The attempted conversion of a character string to a number failed because the character string was not a valid numeric literal. Only numeric fields or character fields containing numeric data may be used in arithmetic functions or expressions. Only numeric fields may be added to or subtracted from dates.Action:Check the character strings in the function or expression. Check that they contain only numbers, a sign, a decimal point, and the character "E" or "e" and retry the operation.

Complex Select statement advise needed please

Hey there. I was wondering if someone could advise me whether or not i've
writted an effective/efficent stored procedure.
Basically the below procedure will be run from a .net application and the
values passed the the parameters will be 1 or null. It will allow the user
to select as many or as little options with like from a checkbox list and
based on what is entered a 1 or null value will be passed in and a results
set passed back.
I was wondering if this is the best way to do such a query or am i on the
wrong track below works fine but I don't know if its the best way to go abou
t
things.
I'd also like to try and order the results somehow but i'm not sure how to
do this as I've know way of knowing how many of the results are part of each
group. The table i'm querying looks like this.
u_forname u_surname b_publications b_consultation b_freedom b_policyt
etc
Stephen Cairns 0 1
0 0
Steve Jones 1 0
1 0
Laura McCall 1 0
0 0
Andrea Jones 0 0
0 1
etc.................
Basically when users can search the table for results equal to 1 from the
fields which they select in the checkbox list.
I hope someone is able to advise me. Thanks for your help
Here is the stored procedure
CREATE PROCEDURE [RegisteredUsers_SpecificSubscribers]
@.publications int,
@.consultation int,
@.freedom int,
@.judgments int,
@.legislation int,
@.policy int,
@.press int,
@.questions int,
@.strategies int,
@.targets int,
@.using int,
@.judgment int ,
@.sentence int,
@.practice int,
@.family int
AS
SET NOCOUNT ON
SELECT u_logon_name, u_firstname, u_surname, u_account_name
FROM UserObject
WHERE
[b_publications] = @.publications OR
([b_consultation] = @.consultation) OR
([b_freedom] = @.freedom) OR
([b_judgments] = @.judgments) OR
([b_legislation] = @.legislation) OR
([b_policy] = @.policy) OR
([b_press] = @.press) OR
([b_questions] = @.questions) OR
([b_strategies] = @.strategies) OR
([b_targets] = @.targets) OR
([b_using] = @.using) OR
([b_judgment] = @.judgment) OR
([b_sentence] = @.sentence) OR
([b_practice] = @.practice) OR
([b_family] = @.family)
GOStephen
Read up this article
http://www.sommarskog.se/dyn-search.html
"Stephen" <Stephen@.discussions.microsoft.com> wrote in message
news:E693AF7A-FA77-4E90-8F5B-4F944E0E3C91@.microsoft.com...
> Hey there. I was wondering if someone could advise me whether or not i've
> writted an effective/efficent stored procedure.
> Basically the below procedure will be run from a .net application and the
> values passed the the parameters will be 1 or null. It will allow the
user
> to select as many or as little options with like from a checkbox list and
> based on what is entered a 1 or null value will be passed in and a results
> set passed back.
> I was wondering if this is the best way to do such a query or am i on the
> wrong track below works fine but I don't know if its the best way to go
about
> things.
> I'd also like to try and order the results somehow but i'm not sure how to
> do this as I've know way of knowing how many of the results are part of
each
> group. The table i'm querying looks like this.
> u_forname u_surname b_publications b_consultation b_freedom b_policyt
> etc
> Stephen Cairns 0 1
> 0 0
> Steve Jones 1 0
> 1 0
> Laura McCall 1 0
> 0 0
> Andrea Jones 0 0
> 0 1
> etc.................
> Basically when users can search the table for results equal to 1 from the
> fields which they select in the checkbox list.
> I hope someone is able to advise me. Thanks for your help
> Here is the stored procedure
> CREATE PROCEDURE [RegisteredUsers_SpecificSubscribers]
> @.publications int,
> @.consultation int,
> @.freedom int,
> @.judgments int,
> @.legislation int,
> @.policy int,
> @.press int,
> @.questions int,
> @.strategies int,
> @.targets int,
> @.using int,
> @.judgment int ,
> @.sentence int,
> @.practice int,
> @.family int
> AS
> SET NOCOUNT ON
> SELECT u_logon_name, u_firstname, u_surname, u_account_name
> FROM UserObject
> WHERE
> [b_publications] = @.publications OR
> ([b_consultation] = @.consultation) OR
> ([b_freedom] = @.freedom) OR
> ([b_judgments] = @.judgments) OR
> ([b_legislation] = @.legislation) OR
> ([b_policy] = @.policy) OR
> ([b_press] = @.press) OR
> ([b_questions] = @.questions) OR
> ([b_strategies] = @.strategies) OR
> ([b_targets] = @.targets) OR
> ([b_using] = @.using) OR
> ([b_judgment] = @.judgment) OR
> ([b_sentence] = @.sentence) OR
> ([b_practice] = @.practice) OR
> ([b_family] = @.family)
> GO

complex SELECT Statement

TABLE : USER
USERID
1
2

TABLE : TIME
TIMEID|USERID|RT|OT|DOT|DATE
1|1|8|2|1|2004-02-01
2|1|8|2|0|2004-02-02

3|2|8|0|0|2004-02-01
4|2|8|2|2|2004-02-02

RT : Regular Time
OT : Over-Time
DOT : Double Over-Time

I need to write a query to display the results in this way

USERID|DATE|TIME
1|2004-02-01|8
1|2004-02-01|2
1|2004-02-01|1

1|2004-02-02|8
1|2004-02-02|2

2|2004-02-01|8
2|2004-02-02|8
2|2004-02-02|2
2|2004-02-02|2

basically, the time entries for each user each day , seperate rows for RT, OT, DOT if they are not equal to 0

ive been breaking my head on this for quite a while. any help is appreciated.

thankscan you detail the TIME column in your result

what do you want in this column ?|||never mind my last post

just understood...

I'm checking for the query now|||this should do

sort the query in the wanted order

select date, users.userid, time from users
inner join (
select date, userid, rt as time from time where rt <>'0'
union
select date, userid, ot from time where ot <>'0'
union
select date, userid, dot from time where dot <>'0') detail_time
on detail_time.userid=users.userid
order by date, users.userid asc|||thanks karolyn,
u saved my day !!

reg
db_montreal|||and it's only starting in montreal