Sunday, March 11, 2012
complicated use of select and count.
I have 2 tables, with a 1-m relationship between them and I am trying
to design a query that seems to beyond what sql can do.
Lets say Table A, has the 1 one side of the relationship and table B
the many. Basically I want a query that returns a list of some or all
entries in Table A (thats the easy bit) and a count of the total
number of records in Table B that meet certain criteria. It seems like
what I want is a where clause for each count clause, rather than a
single where clause for the whole query
TableA has a PrimaryKey of MasterID and TableB has a foreign key to it
also called MasterID
Something like Select TableA.MasterID, COUNT( TableB.* where
TableB.Foo = bar) as 'BarFooCount', COUNT(TableB.* where
TableB.Category = 'Sample') as 'SampleCount', COUNT(TableB.* where
TableB.Category = 'Macro' or TableB.Category = 'Micro') as
'MacroOrMicroCount'
FROM TableA, TableB,
Inner Join blah blah blah;
Basically to get a query back that lists each TableA item, along with
summary information about each TableAs TableB records. It doesnt seem
like I can put where clauses in count clauses so can this be done in
SQL another way?Here's on option, based on Adventureworks database:
SELECT
soh.SalesOrderID
,soh.OrderDate
,(SELECT COUNT(*) FROM Sales.SalesOrderDetail AS sod
WHERE sod.SalesOrderID = soh.SalesOrderID) AS NoOrders
FROM Sales.SalesOrderHeader AS soh
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://sqlblog.com/blogs/tibor_karaszi
"Oolis Kraprin" <Oolis.Kraprin@.googlemail.com> wrote in message
news:bc3c3456-7d89-4533-8171-91926ada7bf4@.m34g2000hsb.googlegroups.com...
> Hi,
> I have 2 tables, with a 1-m relationship between them and I am trying
> to design a query that seems to beyond what sql can do.
> Lets say Table A, has the 1 one side of the relationship and table B
> the many. Basically I want a query that returns a list of some or all
> entries in Table A (thats the easy bit) and a count of the total
> number of records in Table B that meet certain criteria. It seems like
> what I want is a where clause for each count clause, rather than a
> single where clause for the whole query
> TableA has a PrimaryKey of MasterID and TableB has a foreign key to it
> also called MasterID
> Something like Select TableA.MasterID, COUNT( TableB.* where
> TableB.Foo = bar) as 'BarFooCount', COUNT(TableB.* where
> TableB.Category = 'Sample') as 'SampleCount', COUNT(TableB.* where
> TableB.Category = 'Macro' or TableB.Category = 'Micro') as
> 'MacroOrMicroCount'
> FROM TableA, TableB,
> Inner Join blah blah blah;
> Basically to get a query back that lists each TableA item, along with
> summary information about each TableAs TableB records. It doesnt seem
> like I can put where clauses in count clauses so can this be done in
> SQL another way?|||Excellent, that put me in exactly the right direction!
Thank you very much!
On Jan 28, 1:09 pm, "Tibor Karaszi"
<tibor_please.no.email_kara...@.hotmail.nomail.com> wrote:
> Here's on option, based on Adventureworks database:
> SELECT
> soh.SalesOrderID
> ,soh.OrderDate
> ,(SELECT COUNT(*) FROM Sales.SalesOrderDetail AS sod
> WHERE sod.SalesOrderID = soh.SalesOrderID) AS NoOrders
> FROM Sales.SalesOrderHeader AS soh
> --
> Tibor Karaszi, SQL Server MVPhttp://www.karaszi.com/sqlserver/default.asphttp://sqlblog.com/blogs/tibor_karaszi
> "Oolis Kraprin" <Oolis.Krap...@.googlemail.com> wrote in message
> news:bc3c3456-7d89-4533-8171-91926ada7bf4@.m34g2000hsb.googlegroups.com...
> > Hi,
> > I have 2 tables, with a 1-m relationship between them and I am trying
> > to design a query that seems to beyond what sql can do.
> > Lets say Table A, has the 1 one side of the relationship and table B
> > the many. Basically I want a query that returns a list of some or all
> > entries in Table A (thats the easy bit) and a count of the total
> > number of records in Table B that meet certain criteria. It seems like
> > what I want is a where clause for each count clause, rather than a
> > single where clause for the whole query
> > TableA has a PrimaryKey of MasterID and TableB has a foreign key to it
> > also called MasterID
> > Something like Select TableA.MasterID, COUNT( TableB.* where
> > TableB.Foo = bar) as 'BarFooCount', COUNT(TableB.* where
> > TableB.Category = 'Sample') as 'SampleCount', COUNT(TableB.* where
> > TableB.Category = 'Macro' or TableB.Category = 'Micro') as
> > 'MacroOrMicroCount'
> > FROM TableA, TableB,
> > Inner Join blah blah blah;
> > Basically to get a query back that lists each TableA item, along with
> > summary information about each TableAs TableB records. It doesnt seem
> > like I can put where clauses in count clauses so can this be done in
> > SQL another way?|||On Mon, 28 Jan 2008 01:39:51 -0800 (PST), Oolis Kraprin wrote:
>Hi,
>I have 2 tables, with a 1-m relationship between them and I am trying
>to design a query that seems to beyond what sql can do.
>Lets say Table A, has the 1 one side of the relationship and table B
>the many. Basically I want a query that returns a list of some or all
>entries in Table A (thats the easy bit) and a count of the total
>number of records in Table B that meet certain criteria. It seems like
>what I want is a where clause for each count clause, rather than a
>single where clause for the whole query
>TableA has a PrimaryKey of MasterID and TableB has a foreign key to it
>also called MasterID
>Something like Select TableA.MasterID, COUNT( TableB.* where
>TableB.Foo = bar) as 'BarFooCount', COUNT(TableB.* where
>TableB.Category = 'Sample') as 'SampleCount', COUNT(TableB.* where
>TableB.Category = 'Macro' or TableB.Category = 'Micro') as
>'MacroOrMicroCount'
>FROM TableA, TableB,
>Inner Join blah blah blah;
>Basically to get a query back that lists each TableA item, along with
>summary information about each TableAs TableB records. It doesnt seem
>like I can put where clauses in count clauses so can this be done in
>SQL another way?
Hi Oolis,
Here's a basic outline of what you could use:
SELECT A.MasterID,
SUM(CASE WHEN B.Foo = 'Bar' THEN 1 ELSE 0 END) AS FooCount,
SUM(CASE WHEN B.Foo = 'Sample' THEN 1 ELSE 0 END) AS
SampleCount
FROM TableA AS A
INNER JOIN TableB AS B
ON B.MasterID = A.MasterID
GROUP BY A.MasterID;
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis
Complicated Update Statement
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 query based on existing data
well. I need to create a SQL query or queries that updates two columns
based on some business rules. Here's an example of the data:
GroupID complete_num first_num second_num InUse biggest
965423 1.0 1 0
965423 2.0 2 0
965423 3.0 3 0 X
965423 3.1 3 1
965423 3.2 3 2 X
324554 1.0 1 0
324554 2.0 2 0 X X
123456 0.1 0 1
123456 0.2 0 2 X X
Hopefully the above even vaguely lines up for you. The last two
columns are currently blank. The representation above is how I would
like them to look after the queries run. So for the above data, you
have a group id that links all records for one set together. I need to
have the "InUse" box updated with a value of "X" for the highest number
that has zero in the second_num column for a group. I also need the
biggest column set to "X" for the largest number in a particular group,
so 3.1 is larger than 3.0. Keep in mind, I have separated the
complete_num into two columns as there could be a "decimal" value of
"10" which is higher than "1". They are not the same as complete_num
is not really a decimal numeric representation. It's used
programatically for other things. Seperating into two separate columns
allows better sorting of data as complete_num is varchar and first and
second num are integer. You will also see the case, 123456,where there
is no zero in the second_num column. In this case, the highest
second_num value will have both set to "X". Any help would be
appreciated and SQL queries are prefered over any procedures/functions
as this is a one time query I need to run against the database. If you
need further clarification or more examples, please let me know.
Thanks.
JRAlso note that there is of course a unique incremental column in the
table. For arguements sake we can say U_ID. Also these records could
be in any order by default in the database. Not necessarily grouped
together as shown above.|||JR (jriker1@.yahoo.com) writes:
> OK folks, may have a tough one or perhaps just not thinking it through
> well. I need to create a SQL query or queries that updates two columns
> based on some business rules. Here's an example of the data:
> GroupID complete_num first_num second_num InUse biggest
> 965423 1.0 1 0
> 965423 2.0 2 0
> 965423 3.0 3 0 X
> 965423 3.1 3 1
> 965423 3.2 3 2 X
> 324554 1.0 1 0
> 324554 2.0 2 0 X X
> 123456 0.1 0 1
> 123456 0.2 0 2 X X
> Hopefully the above even vaguely lines up for you. The last two
> columns are currently blank. The representation above is how I would
> like them to look after the queries run. So for the above data, you
> have a group id that links all records for one set together. I need to
> have the "InUse" box updated with a value of "X" for the highest number
> that has zero in the second_num column for a group. I also need the
> biggest column set to "X" for the largest number in a particular group,
> so 3.1 is larger than 3.0.
It is always a good idea for this sort of question to include CREATE
TABLE statements for the table, and the sample data as INSERT statements.
That makes it easy to copy-and-paste into a query tool, to develop a
tested solution.
Thus, this is an untested solution:
BEGIN TRANSACTION
UPDATE tbl
SET biggest = 0,
inuse = 0
UPDATE tbl
SET biggest = 1
FROM tbl a
WHERE EXISTS (SELECT *
FROM (SELECT GroupID,
biggest = MAX(100000 * first_num + second_num)
FROM tbl
GROUP BY GroupID) AS big
WHERE a.big = big.GroupID
AND a.first_num * 1000000 + a.second_num = big.biggest)
UPDATE tbl
SET inuse = 1
FROM tbl a
JOIN (SELECT GroupID, first_num = MAX(first_num)
FROM tbl
WHERE second_num = 0
GROUP BY GroupID) AS inuse ON a.GroupID = inuse.GroupID
AND a.first_num = inuse.first_num
AND a.second_num = 0
UPDATE tbl
SET inuse = 1
FROM tbl a
WHERE a.biggest = 1
AND NOT EXISTS (SELECT *
FROM tbl b
WHERE a.GroupID = b.GroupID
AND a.insue = 1)
COMMIT TRANSACTION
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks Erland. SQL Query Analyser is complaining about a syntax
problem with the '=' on "biggest = MAX(100000 * first_num +
second_num)" in the second update and "JOIN (SELECT GroupID,
first_num = MAX(first_num)" in the ghird.|||JR,
I think you can say this more simply: Update InUse to X
for the largest second_num value in the group *counting 0
as the largest*, and the largest first_num value in the case of
a tie. Update biggest to X for the largest first_num value
in the group, and the largest second_num value in the case
of a tie.
There is a more compact solution than Erland's in SQL Server 2005:
with T2 as (
select
*,
rank() over (partition by GroupID order by first_num desc,
case when second_num = 0 then 2147364827 else second_num end desc)
as rk1,
rank() over (partition by GroupID order by second_num desc,
first_num desc) as rk2
from #T
)
update T2 set
InUse = case when rk1 = 1 then 'X' else InUse end,
biggest = case when rk2 = 1 then 'X' else biggest end
where rk1 = 1 or rk2 = 1
Steve Kass
Drew University
JR wrote:
>OK folks, may have a tough one or perhaps just not thinking it through
>well. I need to create a SQL query or queries that updates two columns
>based on some business rules. Here's an example of the data:
>GroupID complete_num first_num second_num InUse biggest
>965423 1.0 1 0
>965423 2.0 2 0
>965423 3.0 3 0 X
>965423 3.1 3 1
>965423 3.2 3 2 X
>324554 1.0 1 0
>324554 2.0 2 0 X X
>123456 0.1 0 1
>123456 0.2 0 2 X X
>
>Hopefully the above even vaguely lines up for you. The last two
>columns are currently blank. The representation above is how I would
>like them to look after the queries run. So for the above data, you
>have a group id that links all records for one set together. I need to
>have the "InUse" box updated with a value of "X" for the highest number
>that has zero in the second_num column for a group. I also need the
>biggest column set to "X" for the largest number in a particular group,
>so 3.1 is larger than 3.0. Keep in mind, I have separated the
>complete_num into two columns as there could be a "decimal" value of
>"10" which is higher than "1". They are not the same as complete_num
>is not really a decimal numeric representation. It's used
>programatically for other things. Seperating into two separate columns
>allows better sorting of data as complete_num is varchar and first and
>second num are integer. You will also see the case, 123456,where there
>is no zero in the second_num column. In this case, the highest
>second_num value will have both set to "X". Any help would be
>appreciated and SQL queries are prefered over any procedures/functions
>as this is a one time query I need to run against the database. If you
>need further clarification or more examples, please let me know.
>Thanks.
>JR
>
>|||On 9 Apr 2006 07:36:13 -0700, JR wrote:
>OK folks, may have a tough one or perhaps just not thinking it through
>well. I need to create a SQL query or queries that updates two columns
>based on some business rules. Here's an example of the data:
(snip)
Hi JR,
If these columns should be calculated based on the data, why store them
at all? I would only recommend that if updates are very infrequent,
queries of the data are very frequent and the table is large, or if
these columns need to capture a moment in time and stay unchanged after
that, even if the underlying data does change.
In one of the latter cases, use Erland's suggestion. Otherwise, drop the
columns from the table and set up a view instead:
CREATE VIEW ChooseGoodName
AS
SELECT a.GroupID, a.complete_num, a.first_num, a.second_num,
CASE WHEN a.first_num = b.first_num
AND a.second_num = 0
THEN 'X' -- Latest X.0
WHEN a.first_num = 0
AND a.second_num = b.second_num
THEN 'X' -- Latest 0.Y
ELSE ''
END AS InUse,
CASE WHEN b.first_num = a.first_num
AND b.second_num = a.second_num
THEN 'X'
ELSE ''
END AS biggest
FROM YourTable AS a
INNER JOIN (SELECT GroupID, complete_num, first_num, second_num
FROM YourTable AS c
WHERE NOT EXISTS (SELECT *
FROM YourTable AS d
WHERE d.GroupID = c.GroupID
AND ( d.first_num > c.first_num
OR ( d.first_num = c.first_num
AND d.second_num > c.second_num))
) ) AS b
ON b.GroupID = a.GroupID
(Untested - see www.aspfaq.com/5006 if you prefer a tested reply)
Hugo Kornelis, SQL Server MVP|||JR (jriker1@.yahoo.com) writes:
> Thanks Erland. SQL Query Analyser is complaining about a syntax
> problem with the '=' on "biggest = MAX(100000 * first_num +
> second_num)" in the second update and "JOIN (SELECT GroupID,
> first_num = MAX(first_num)" in the ghird.
Yes, as I said the code was untested for reasons I explained. I assume
that you are able to weed out trivial syntax errors on your own. If not,
please include CREATE TABLE statements and the sample data in INSERT
statements, to make testing easy.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||As requested, here is a table creation script and some minimal data to
limit the length of the message. Also Hugo's view is great however
since this data is for one time use, would imagine updates to the
existing data would be preferable over introducing a new view into the
mix. If not updating the data directly based on the view would now be
a simple matter when you introduce the Id from the original table into
the view.
CREATE TABLE [abcd].[dbo].[TBL1
(Id,GroupId,complete_num,first_num,secon
d_num)] (
[Id] int NOT NULL,
[GroupID] nvarchar (60) NULL,
[complete_num] varchar (255) NULL,
[first_num] integer,
[second_num] integer,
[InUse] varchar (2) NULL,
[biggest] varchar (2) NULL,
)
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(91510,ABC1235,2.0,2,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(89377,ABC1235,2.1,2,1);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(89371,ABC1235,2.2,2,2);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1310,M123456,1.0,1,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1309,M123456,2.0,2,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1311,M123456,3.0,3,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1312,M123456,4.0,4,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1315,M123456,5.0,5,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1318,M123456,6.0,6,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1319,M123456,7.0,7,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1317,M123456,8.0,8,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(5342,M123456,9.0,9,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(5346,M123456,10.0,10,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(5756,M123456,11.0,11,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(6315,M123456,12.0,12,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(6604,M123456,13.0,13,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(6920,M123456,14.0,14,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(1002,M123456,15.0,15,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES
(4023,ARDFO32,0.1,0,1);|||Your programs will be total nightmares and crap until you learn how to
design a schema.
Look at the DDL; do you really have a NCHAR(60) grpoup identifier? In
Chinese' Wel;l;, since you allowed it, you will get one! Why do you
have redundant split attributes (i.e. first_num || second_num =
complete_num)? Let's spit on normalization!! I also love the clear,
meaningful names of the data elements. Tell us what a thing is, not
its sequential order inside another column. Logical not physical
descriptions.
There are no keys, no constraints. This is not a table at all! And
you invented your own syntax for CREATE TABLE.
Your idea of updatind computed columns is a way to mimic punch cards.
Back in the 1950-60's we had to store those things in the physical
card, like you are doing now.
Making a guess, if you normalized your schema, had a key and followed
the baisc data modeling rules, would this nightmare look more like
this? Better names that show subordination (well, Foobar is a dummy
name, but that is all you gave us)
CREATE TABLE Foobar
(group_id CHAR(6) NOT NULL
CHECK (group_id LIKE '[0-9][0-9][0-9][0-9][0-9][0-9]')
section_nbr INTEGER DEFAULT 1 NOT NULL
CHECK (section_num >= 0),
subsection_nbr INTEGER DEFAULT 0 NOT NULL
CHECK (subsection_num >= 0),
PRIMARY KEY (group_id, section_nbr, subsection_nbr));
Do you need a constaint to assure that the subsections are in sequence?
Is there a check digit rule in the group_id? 90% of the work in RDBMS
is done in the DDL!!
SQL does not have links; it has REFERENCES and grouping. Totally
different concepts, based on sets and not pre-RDBMS file and pointer
systems. Rows are nothing whatsoever like records.
Now, the answer to your question is a VIEW, not a "punch cards and bit
flags" solution via updates.
CREATE VIEW InUseFoobar (group_id, section_nbr, subsection_nbr)
AS
SELECT group_id, MAX(section_nbr), 0
FROM Foobar
WHERE subsection = 0
GROUP BY group_id) ;
CREATE VIEW MaxFoobar (group_id, section_nbr, subsection_nbr)
AS
SELECT group_id, section_nbr, MAX(subsection_nbr)
FROM Foobar AS F1, InUseFoobar AS U1
WHERE F1.group_id = .U1.group_id
AND F1.section_nbr = .U1.section_nbr
GROUP BY group_id, section_nbr ;
<<untested>>|||JR (jriker1@.yahoo.com) writes:
> As requested, here is a table creation script and some minimal data to
> limit the length of the message. Also Hugo's view is great however
> since this data is for one time use, would imagine updates to the
> existing data would be preferable over introducing a new view into the
> mix. If not updating the data directly based on the view would now be
> a simple matter when you introduce the Id from the original table into
> the view.
Below is a tested version of my script. I'm not sure that I understand
the syntax errors you mentioned; I did not get these. I include
your original script, with small changes. Note that I've made inuse
and biggest into bit columns; I did this as I used 0 and 1 in my script.
Beware that things get wrapped in news transport!
CREATE TABLE [dbo].[TBL1]
(
[Id] int NOT NULL,
[GroupId] nvarchar (60) NULL,
[complete_num] varchar (255) NULL,
[first_num] integer,
[second_num] integer,
[inuse] bit NULL,
[biggest] bit NULL,
)
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (9151
0,'ABC1235',2.0,2,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (8937
7,'ABC1235',2.1,2,1);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (8937
1,'ABC1235',2.2,2,2);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1310
,'M123456',1.0,1,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1309
,'M123456',2.0,2,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1311
,'M123456',3.0,3,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1312
,'M123456',4.0,4,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1315
,'M123456',5.0,5,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1318
,'M123456',6.0,6,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1319
,'M123456',7.0,7,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1317
,'M123456',8.0,8,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (5342
,'M123456',9.0,9,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (5346
,'M123456',10.0,10,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (5756
,'M123456',11.0,11,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (6315
,'M123456',12.0,12,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (6604
,'M123456',13.0,13,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (6920
,'M123456',14.0,14,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (1002
,'M123456',15.0,15,0);
INSERT INTO TBL1 (Id,GroupId,complete_num,first_num,secon
d_num) VALUES (4023
,'ARDFO32',0.1,0,1);
go
BEGIN TRANSACTION
UPDATE TBL1
SET biggest = 0,
inuse = 0
UPDATE TBL1
SET biggest = 1
FROM TBL1 a
WHERE EXISTS (SELECT *
FROM (SELECT GroupId,
biggest = MAX(100000 * first_num + second_num)
FROM TBL1
GROUP BY GroupId) AS big
WHERE a.GroupId = big.GroupId
AND a.first_num * 100000 + a.second_num = big.biggest)
UPDATE TBL1
SET inuse = 1
FROM TBL1 a
JOIN (SELECT GroupId, first_num = MAX(first_num)
FROM TBL1
WHERE second_num = 0
GROUP BY GroupId) AS inuse ON a.GroupId = inuse.GroupId
AND a.first_num = inuse.first_num
AND a.second_num = 0
UPDATE TBL1
SET inuse = 1
FROM TBL1 a
WHERE a.biggest = 1
AND NOT EXISTS (SELECT *
FROM TBL1 b
WHERE a.GroupId = b.GroupId
AND b.inuse = 1)
COMMIT TRANSACTION
SELECT * FROM TBL1
go
drop table TBL1
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
complicated update (for me)
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 Task Please Help
I have a requirment to pull a query that would result in something like the
following:
[Service Line] | [POCount] | W
W
MNS 15 3
2 10
etc...
I create a temp table and dump the data into it and find the W
using a function.
My problme is that I can't get it to group like indicated above.
Below is my entire code, excluding the Function.
Please Help... I'm desperate :)
John.
CREATE PROCEDURE dbo.usp_RPT_OPW_FLASH
@.startdate SmallDateTime,
@.enddate SmallDateTime
AS
SET NOCOUNT ON
BEGIN TRANSACTION
---
--Create Temporary Table To Hold the data
---
Create Table #tmpOPW_FLASH (
[Service Line] VarChar(50),
[Total Of PONumber]INT,
RC DateTime,
RS DateTime,
CycleTime Decimal(18,2),
W
)
---
--Insert Data into temporary table for DATE_ORDERED (Issued)
---
INSERT INTO #tmpOPW_FLASH([Service Line], [Total Of PONumber], RC, RS)
SELECT T1.DataSource AS [Service Line], COUNT(T1.PoNumber) AS [Total Of
PONumber],
T1.REQCreateDate + CAST(T1.REQCreateTime AS DATETIME) AS RC,
T1.ReqSubmitDate + CAST(T1.ReqSubmitTime AS DATETIME) AS RS
FROM OPW T1 INNER JOIN
(SELECT PoNumber
FROM OPW
GROUP BY PoNumber
HAVING COUNT(*) > 1) T2 ON T1.PoNumber = T2.PoNumber
WHERE (T1.ReqSubmitDate BETWEEN @.startdate AND @.enddate)
GROUP BY T1.DataSource, T1.REQCreateDate + CAST(T1.REQCreateTime AS
DATETIME), T1.ReqSubmitDate + CAST(T1.ReqSubmitTime AS DATETIME)
---
--UPDATE CycleTime and W
---
UPDATE #tmpOPW_FLASH
SET CycleTime = DateDiff(hh, RC, RS),
W
----
SELECT [Service Line], [Total Of PONumber], W
FROM #tmpOPW_FLASH
GROUP BY [Service Line], [Total Of PONumber], W
DROP TABLE #tmpOPW_FLASH
COMMIT TRANSACTIONI think that you wont need your Temp table although i cant understand your
intention, but these update can be done in an inline statement, because you
are only calling a function to do this. Please post some DDL and smaple data
which can be read a bit better then the pasting of your last post, and well
fix it together :-)
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"John Rugo" <jrugo@.patmedia.net> schrieb im Newsbeitrag
news:uAbrsS1SFHA.3544@.TK2MSFTNGP10.phx.gbl...
> Hi All,
> I have a requirment to pull a query that would result in something like
> the following:
> [Service Line] | [POCount] | W
> W
> MNS 15 3 2
> 10
> etc...
> I create a temp table and dump the data into it and find the W
> using a function.
> My problme is that I can't get it to group like indicated above.
> Below is my entire code, excluding the Function.
> Please Help... I'm desperate :)
> John.
>
> CREATE PROCEDURE dbo.usp_RPT_OPW_FLASH
> @.startdate SmallDateTime,
> @.enddate SmallDateTime
> AS
> SET NOCOUNT ON
> BEGIN TRANSACTION
> ---
> --Create Temporary Table To Hold the data
> ---
> Create Table #tmpOPW_FLASH (
> [Service Line] VarChar(50),
> [Total Of PONumber]INT,
> RC DateTime,
> RS DateTime,
> CycleTime Decimal(18,2),
> W
> )
> ---
> --Insert Data into temporary table for DATE_ORDERED (Issued)
> ---
> INSERT INTO #tmpOPW_FLASH([Service Line], [Total Of PONumber], RC, RS)
> SELECT T1.DataSource AS [Service Line], COUNT(T1.PoNumber) AS [Total Of
> PONumber],
> T1.REQCreateDate + CAST(T1.REQCreateTime AS DATETIME) AS RC,
> T1.ReqSubmitDate + CAST(T1.ReqSubmitTime AS DATETIME) AS RS
> FROM OPW T1 INNER JOIN
> (SELECT PoNumber
> FROM OPW
> GROUP BY PoNumber
> HAVING COUNT(*) > 1) T2 ON T1.PoNumber = T2.PoNumber
> WHERE (T1.ReqSubmitDate BETWEEN @.startdate AND @.enddate)
> GROUP BY T1.DataSource, T1.REQCreateDate + CAST(T1.REQCreateTime AS
> DATETIME), T1.ReqSubmitDate + CAST(T1.ReqSubmitTime AS DATETIME)
> ---
> --UPDATE CycleTime and W
> ---
> UPDATE #tmpOPW_FLASH
> SET CycleTime = DateDiff(hh, RC, RS),
> W
> ----
> SELECT [Service Line], [Total Of PONumber], W
> FROM #tmpOPW_FLASH
> GROUP BY [Service Line], [Total Of PONumber], W
> DROP TABLE #tmpOPW_FLASH
> COMMIT TRANSACTION
>|||Your approach is too procedural. Create a table of reporting periods:
CREATE TABLE ReportPeriods
(period_name CHAR (20) NOT NULL PRIMARY KEY,
period_start_date DATETIME NOT NULL,
period_end_date DATETIME NOT NULL,
CHECK (period_start_date < period_end_date));
Then write something like:
SELECT service_line, po_cnt,
CASE WHEN OPW.some_date BETWEEN R1.period_start_date and
period_end_date
AND R1.period_name = ''W
THEN 1 ELSE 0 END AS w
etc.
FROM ReportPeriods AS R1, OPW
WHERE ... ;
In short, think in terms of joins and not computations.
You are also making the classic Newbie error of trying to format the
data and the column headers in the backend. The whole point of a
tiered architecture is that you do this only in the front end.
Also, please post DDL, so that people do not have to guess what the
keys, constraints, Declarative Referential Integrity, datatypes, etc.
in your schema are. Sample data is also a good idea, along with clear
specifications.|||/* general this is the type of data and structure I am working with.
I need to show the data as indicated before below:
Basically I did this on the Applications Front end and sent in a Dynamic SQL
string. I know there must be a way to do this via a procedure; I'm just
learning the more advanced stuff now.
One of my current delemas is getting the W
columniarly as show below.
*/
CREATE TABLE OPW (
DataSource VarChar(50),
PoNumber VarChar(22),
ReqCreateDate datetime
ReqCreateTime varchar(10),
ReqSubmitDate datetime
ReqSubmitTime varchar(10),
NamePrep varchar(240))
INSERT INTO OPW ('MNS', PW02939, '04/01/2005', '11:39:58', '04/04/2005',
'12:30:00', 'JOHN')
INSERT INTO OPW ('MNS', PW02939, '04/01/2005', '11:39:58', '04/04/2005',
'12:30:00', 'BILL')
INSERT INTO OPW ('MNS', PW02937, '04/03/2005', '11:39:58', '04/07/2005',
'12:30:00', 'JOHN')
INSERT INTO OPW ('MNS', PW02934, '04/20/2005', '11:39:58', '04/23/2005',
'12:30:00', 'BOB')
INSERT INTO OPW ('MNS', PW02937, '04/03/2005', '11:39:58', '04/07/2005',
'12:30:00', 'JOHN')
INSERT INTO OPW ('MNS', PW02933, '04/17/2005', '11:39:58', '04/20/2005',
'12:30:00', 'JOHN')
/*
Service Line PO Created By Total Of PONumber 04/02/2005 04/09/2005
04/16/2005 04/23/2005 04/30/2005
EVPN MURPHY, ANTOINETTE J 4 4
MNS ADELER, LISA 13 11 2
MNS ARAGON, JENNIFER 59 35 24
MNS BERIG, CARI 22 12 10
MNS KIRBY, DANIEL 101 76 25
MNS KRENKEL, LISA R 60 60
MNS LEONARDELLI, JOHN MICHAEL 143 40 103
MNS MADSEN, SHANE 24 14 10
MNS MURPHY, ANTOINETTE J 3 3
MNS PYELL, CLAUDETTE 11 11
MNS SCARBOROUGH, MERNA 80 10 70
MNS WHALEY, LEE 6 6
*/
"Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:OwD31a1SFHA.580@.TK2MSFTNGP15.phx.gbl...
>I think that you wont need your Temp table although i cant understand
>your intention, but these update can be done in an inline statement,
>because you are only calling a function to do this. Please post some DDL
>and smaple data which can be read a bit better then the pasting of your
>last post, and well fix it together :-)
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
> "John Rugo" <jrugo@.patmedia.net> schrieb im Newsbeitrag
> news:uAbrsS1SFHA.3544@.TK2MSFTNGP10.phx.gbl...
>|||Sorry i read for about 10 minutes you ddl and output (whch is formatted in a
strange way) and even now i dont know what you are going to do. I am
willing to help you but i cant understand your question. :-(
If this oist will last too long and i loose track of it, jst write me an
email to see wheter we can check it off ngposting and post the results back.
Jens Suessmeyer.
"John Rugo" <jrugo@.patmedia.net> schrieb im Newsbeitrag
news:%23RbaS61SFHA.900@.TK2MSFTNGP10.phx.gbl...
> /* general this is the type of data and structure I am working with.
> I need to show the data as indicated before below:
> Basically I did this on the Applications Front end and sent in a Dynamic
> SQL string. I know there must be a way to do this via a procedure; I'm
> just learning the more advanced stuff now.
> One of my current delemas is getting the W
> columniarly as show below.
> */
> CREATE TABLE OPW (
> DataSource VarChar(50),
> PoNumber VarChar(22),
> ReqCreateDate datetime
> ReqCreateTime varchar(10),
> ReqSubmitDate datetime
> ReqSubmitTime varchar(10),
> NamePrep varchar(240))
> INSERT INTO OPW ('MNS', PW02939, '04/01/2005', '11:39:58', '04/04/2005',
> '12:30:00', 'JOHN')
> INSERT INTO OPW ('MNS', PW02939, '04/01/2005', '11:39:58', '04/04/2005',
> '12:30:00', 'BILL')
> INSERT INTO OPW ('MNS', PW02937, '04/03/2005', '11:39:58', '04/07/2005',
> '12:30:00', 'JOHN')
> INSERT INTO OPW ('MNS', PW02934, '04/20/2005', '11:39:58', '04/23/2005',
> '12:30:00', 'BOB')
> INSERT INTO OPW ('MNS', PW02937, '04/03/2005', '11:39:58', '04/07/2005',
> '12:30:00', 'JOHN')
> INSERT INTO OPW ('MNS', PW02933, '04/17/2005', '11:39:58', '04/20/2005',
> '12:30:00', 'JOHN')
>
> /*
> Service Line PO Created By Total Of PONumber 04/02/2005 04/09/2005
> 04/16/2005 04/23/2005 04/30/2005
> EVPN MURPHY, ANTOINETTE J 4 4
> MNS ADELER, LISA 13 11 2
> MNS ARAGON, JENNIFER 59 35 24
> MNS BERIG, CARI 22 12 10
> MNS KIRBY, DANIEL 101 76 25
> MNS KRENKEL, LISA R 60 60
> MNS LEONARDELLI, JOHN MICHAEL 143 40 103
> MNS MADSEN, SHANE 24 14 10
> MNS MURPHY, ANTOINETTE J 3 3
> MNS PYELL, CLAUDETTE 11 11
> MNS SCARBOROUGH, MERNA 80 10 70
> MNS WHALEY, LEE 6 6
> */
> "Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
> in message news:OwD31a1SFHA.580@.TK2MSFTNGP15.phx.gbl...
>
Complicated SQL Select help needed
Hi,
My users table contains a field called researchInterestId which looks like this: 1, 5, 10
This is because users where allows to select multiple options when choosing their research interests.
I have another table which contains the names of those research interests, which looks like this:
researchInterestId researchInterestName
1 Biology
2 Cancer
My question is, when selecting my list of users, i wish to also display the names of their research interests. I know how to inner join but im not sure in this case as there are multiple values (1, 5, 10)
Hope that makes sense and that someone can point me in the right direction or let me know what this type of query is called?
Thanks
Sam
You can create a function as shown here:http://weblogs.sqlteam.com/dinakar/archive/2007/03/28/60150.aspx in the comments and use it to join with the researchinterests table to get the description.
|||It worked perfectly, thanks so much!
complicated sql query
I have a pretty complicated query (at least for me) I'd need some help
on.
Here's the thing.
I have an occupancy sensor that logs a timestamp in a log table every
10 seconds when a person is detected.
If no one is detected, no log is written.
Now I need to count the number of visit and the duration on that room
so I built that query:
SELECT TOP (100) PERCENT ActivityID, LocationName, Timestamp,
DATEDIFF(ss,
(SELECT MAX(Timestamp)
FROM dbo.tbl_ActivityLog AS
Previous
WHERE (LocationName =
[Current].LocationName) AND (Timestamp < [Current].Timestamp) AND
(DATEDIFF(ss,
Timestamp, [Current].Timestamp) <= 15)), Timestamp) AS Duration
FROM dbo.tbl_ActivityLog AS [Current]
That query works well, retrieving a row for every 10 seconds when
someone is in the room and with a Duration=NULL when the difference
between 2 detection is > 15 s to count that case as a different visit
(15 because sometimes is the sensor is too busy, it takes more than 10
seconds to notify)
Here's a simple example of data retrieved with that query:
ActivityID Location Timestamp Duration
1 loc1 8/13/2007 1:18:03 AM NULL
2 loc1 8/13/2007 1:18:13 AM 10
3 loc1 8/13/2007 1:18:23 AM 10
4 loc1 8/13/2007 3:34:50 AM NULL
When the duration is null, I know than between the last visit and the
current visit, more than 15 seconds passed so I have to count it as a
new visit.
Now my question:
I would like to have a query that will give me:
- the number of visits for a location,
- the duration for each visit.
Thanks for your help, and sorry to be so verbose
Patrice
On Tue, 14 Aug 2007 11:40:20 -0700, plevexier@.gmail.com wrote:
>Hello all,
>I have a pretty complicated query (at least for me) I'd need some help
>on.
>Here's the thing.
(snip)
>Now my question:
>I would like to have a query that will give me:
>- the number of visits for a location,
>- the duration for each visit.
>
>Thanks for your help, and sorry to be so verbose
Hi Patrice,
Could you please post the table structure (as a CREATE TABLE statement,
including all constraints, properties, and indexes - though you may omit
irrelevant columns), some well-chosen rows of sample data (as INSERT
statemtents), and expected results? See www.aspfaq.com/5006 as well.
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis
complicated sql query
I have a pretty complicated query (at least for me) I'd need some help
on.
Here's the thing.
I have an occupancy sensor that logs a timestamp in a log table every
10 seconds when a person is detected.
If no one is detected, no log is written.
Now I need to count the number of visit and the duration on that room
so I built that query:
SELECT TOP (100) PERCENT ActivityID, LocationName, Timestamp,
DATEDIFF(ss,
(SELECT MAX(Timestamp)
FROM dbo.tbl_ActivityLog AS
Previous
WHERE (LocationName =
[Current].LocationName) AND (Timestamp < [Current].Timestamp) AND
(DATEDIFF(ss,
Timestamp, [Current].Timestamp) <= 15)), Timestamp) AS Duration
FROM dbo.tbl_ActivityLog AS [Current]
That query works well, retrieving a row for every 10 seconds when
someone is in the room and with a Duration=NULL when the difference
between 2 detection is > 15 s to count that case as a different visit
(15 because sometimes is the sensor is too busy, it takes more than 10
seconds to notify)
Here's a simple example of data retrieved with that query:
ActivityID Location Timestamp Duration
1 loc1 8/13/2007 1:18:03 AM NULL
2 loc1 8/13/2007 1:18:13 AM 10
3 loc1 8/13/2007 1:18:23 AM 10
4 loc1 8/13/2007 3:34:50 AM NULL
When the duration is null, I know than between the last visit and the
current visit, more than 15 seconds passed so I have to count it as a
new visit.
Now my question:
I would like to have a query that will give me:
- the number of visits for a location,
- the duration for each visit.
Thanks for your help, and sorry to be so verbose
PatriceOn Tue, 14 Aug 2007 11:40:20 -0700, plevexier@.gmail.com wrote:
>Hello all,
>I have a pretty complicated query (at least for me) I'd need some help
>on.
>Here's the thing.
(snip)
>Now my question:
>I would like to have a query that will give me:
>- the number of visits for a location,
>- the duration for each visit.
>
>Thanks for your help, and sorry to be so verbose
Hi Patrice,
Could you please post the table structure (as a CREATE TABLE statement,
including all constraints, properties, and indexes - though you may omit
irrelevant columns), some well-chosen rows of sample data (as INSERT
statemtents), and expected results? See www.aspfaq.com/5006 as well.
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis
complicated sql query
I have a pretty complicated query (at least for me) I'd need some help
on.
Here's the thing.
I have an occupancy sensor that logs a timestamp in a log table every
10 seconds when a person is detected.
If no one is detected, no log is written.
Now I need to count the number of visit and the duration on that room
so I built that query:
SELECT TOP (100) PERCENT ActivityID, LocationName, Timestamp,
DATEDIFF(ss,
(SELECT MAX(Timestamp)
FROM dbo.tbl_ActivityLog AS
Previous
WHERE (LocationName = [Current].LocationName) AND (Timestamp < [Current].Timestamp) AND
(DATEDIFF(ss,
Timestamp, [Current].Timestamp) <= 15)), Timestamp) AS Duration
FROM dbo.tbl_ActivityLog AS [Current]
That query works well, retrieving a row for every 10 seconds when
someone is in the room and with a Duration=NULL when the difference
between 2 detection is > 15 s to count that case as a different visit
(15 because sometimes is the sensor is too busy, it takes more than 10
seconds to notify)
Here's a simple example of data retrieved with that query:
ActivityID Location Timestamp Duration
1 loc1 8/13/2007 1:18:03 AM NULL
2 loc1 8/13/2007 1:18:13 AM 10
3 loc1 8/13/2007 1:18:23 AM 10
4 loc1 8/13/2007 3:34:50 AM NULL
When the duration is null, I know than between the last visit and the
current visit, more than 15 seconds passed so I have to count it as a
new visit.
Now my question:
I would like to have a query that will give me:
- the number of visits for a location,
- the duration for each visit.
Thanks for your help, and sorry to be so verbose :)
PatriceOn Tue, 14 Aug 2007 11:40:20 -0700, plevexier@.gmail.com wrote:
>Hello all,
>I have a pretty complicated query (at least for me) I'd need some help
>on.
>Here's the thing.
(snip)
>Now my question:
>I would like to have a query that will give me:
>- the number of visits for a location,
>- the duration for each visit.
>
>Thanks for your help, and sorry to be so verbose :)
Hi Patrice,
Could you please post the table structure (as a CREATE TABLE statement,
including all constraints, properties, and indexes - though you may omit
irrelevant columns), some well-chosen rows of sample data (as INSERT
statemtents), and expected results? See www.aspfaq.com/5006 as well.
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis
complicated SQL help
I have a table (about 3000 rows) where two of the columns have Domain User information.
COL1 has DOMAIN\Username and COL2 has (or SHOULD have) DOMAIN@.username.com
I need to look at each field in COL1 and if exists DOMAIN\username, I need to populate COL2 with username@.DOMAIN.com
Is this possible?very possibleupdate daTable
set COL2 = substring(COL1
,charindex('\',COL1)+1
,LEN(COL1)-charindex('\',COL1)
)
+ '@.' +
left(COL1,charindex('\',COL1)-1)
where coalesce(COL1,'') > ''tip: back up your data before trying this|||Thank you! That's a start! I learn so much from these forums!!
Problem is... I still do not have the .com part of the username@.domain.com in COL2
I also found out that once I populate COL2 correctly, I need to CLEAR any field in COL2 that does not adhere to "username@.domain.com" and then change domain to correctdomain so that all of the poplated fields in COL2 will read username@.correctdomain.com|||Problem is... I still do not have the .com part of the username@.domain.com in COL2well, that's easy, just concatenate '.com' onto the end! ;)|||Thanks.. what about the fields that got pulled over that don't adhere to the username@.Domain.com criteria? Is there a way to clear any fields that are not LIKE username@.Domain.com ?|||What do you have beside DOMAIN\username in the column?
select COl1, COL2
from daTable
where COL1 not like 'DOMAIN%'|||My COL2 is now correct. all fields have username@.DOMAIN.com
What I need to do is clear or delete any fields that do not have specially
username@.domain.com
in other words. I need to keep all fields in COL2 that are LIKE @.DOMAIN.com
and delete all others (some are username@.anotherdomain.com or username@.yetanotherdomain.com)
I tried
Delete from MYTABLE
Where COL2 LIKE '%@.anotherdomain.com%'
but that deleted the whole row.. I need to just clear the field in COL2|||Try this:
UPDATE myTable
SET COL2 = NULL
WHERE COL2 NOT LIKE '%@.theDomainRecordsToKeep.com'|||THANK YOU!!!
This is the code I ended up using..
UPDATE MYTABLE
SET COL2= PARSENAME(REPLACE(COL1, '\', '.'), 1) + '@.' +
PARSENAME(REPLACE(COL1, '\', '.'), 2) + '.com'
WHERE COL1 LIKE '%DOMAIN\%'
go
UPDATE MYTABLE
SET COL2 = Replace(COL2,'DOMAIN','CORRECTDOMAIN')
go
Seems to work..
complicated sql condition query
Hi,
hope someone can help or suggest something to help me with the issue.
I have a list of projects. this list contains all master (parent) and all subprojects(child). when I click on a project I want to be able to retreive information about that project and it's subprojects. here is my delema. I want my sql query to check if project is master or sub. if master then get all data for this project and its subprojects but if it's sub then get data only for that sub. below is a sample data that I hope it clear things up
parent_ID child_id Type projname
--
100 100 P parent_X_proj
100 25 C child_X_proj
100 29 C child_X_proj2
200 200 P parent_Z
300 300 P parent_Y
etc................
this is how my table is constructed. my application passes child_id and what I want is if someone clicks on parent_X_proj I want to be able to retreive the three projects (100,25,29) but if someone clicks on child project (29) then I want only that project.
so I want my query to look for the type and if my type is P (parent) then get all project where parent_id = 100(for example) but if type= C then get child_id = 29.
I know it could be done in stored procedure buy my application cannon executre SP but only sql statements.
Thank you for any help
which version of SS are you using?
declare @.child_id int
set @.child_id = 100
;with proj
as
(
select
child_id, projname, type, 1 as lvl
from
dbo.t1
where
child_id = @.child_id
union all
select
c.child_id, c.projname, c.type, p.lvl + 1 as lvl
from
dbo.t1 as c
inner join
proj as p
on p.child_id = c.parent_id
and ((p.lvl = 1 and p.type = 'P') or (p.lvl > 1 and p.type = 'C'))
)
select
*
from
proj;
AMB
P.S. not tested
|||thank you. I'm using SS 2005. as I mentioned in my post that I can't use Stored Procedure since my application can only execute plain sql statement.
thanks
|||AMB has given you the answer. Your application just needs to form the query and execute it.
Code Snippet
;with proj
as
(
select
child_id, projname, type, 1 as lvl
from
dbo.t1
where
child_id = <selectedValue_goes_here>
union all
select
c.child_id, c.projname, c.type, p.lvl + 1 as lvl
from
dbo.t1 as c
inner join
proj as p
on p.child_id = c.parent_id
and ((p.lvl = 1 and p.type = 'P') or (p.lvl > 1 and p.type = 'C'))
)
select * from proj;
Complicated SELECT Problem
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
complicated select
column, the values of which are comma separated integers. something
like so:
create table foo (
fookey int primary key not null,
foointegerlist1 varchar(50) null,
foointegerlist2 varchar(50) null,
fooprice money null,
foosize int null
)
insert into foo values (1, ',2,3', '1', 10, 100)
insert into foo values (2, '3', '4', null, 100)
insert into foo values (3, ',1,11', ',1,5,6', 10, 100)
insert into foo values (4, ',3,5', ',11', 10, null)
(yes, the leading comma will randomly appear)
unpleasant? yes. scheduled to be redesigned? yes. but for now, this is
what i have to contend with.
the problem i'm having is that there is another table with a very
similar column, like so:
create table foomatch (
foomatchkey int primary key not null,
foomatchintegerlist1 varchar(50) null
foomatchintegerlist2 varchar(50) null,
foomatchprice money null,
foomatchsize int null
)
insert into foomatch values (1, ',2', ',4,5,6', 10, 100)
insert into foomatch values (2, ',1,3,6', ',1', null, null)
the goal of the select statement is to capture all of the rows in the
table foo that "match" the values of a given single row in the foomatch
table. the rules for matching are as follows:
foomatch.foomatchprice = foo.fooprice AND
foomatch.foomatchsize = foo.foosize AND
(this is where it gets dicey for me)
at least ONE of the integer values in foomatch.foomatchintegerlist1
must occur in the foo.foointegerlist1 column AND
at least ONE of the integer values in foomatch.foomatchintegerlist2
must occur in the foo.foointegerlist1 column
where foomatch.foomatchkey = 1 (for example)
i have a user defined function that can turn a comma separated string
value into a single column table. i mention this in case building
tables of the values will make this easier / possible (perhaps with
relational math?)
thanks in advance for any help, and just let me know if you need
clarification,
jasonhi jason,
its quite a long story
use string manipulations to meet the desired solution.
we have several string functions that you can use
thanks,
Jose de Jesus Jr. Mcp,Mcdba
Data Architect
Sykes Asia (Manila philippines)
MCP #2324787
"jason" wrote:
> through no fault of my own, there exists a table with varchar(50)
> column, the values of which are comma separated integers. something
> like so:
> create table foo (
> fookey int primary key not null,
> foointegerlist1 varchar(50) null,
> foointegerlist2 varchar(50) null,
> fooprice money null,
> foosize int null
> )
> insert into foo values (1, ',2,3', '1', 10, 100)
> insert into foo values (2, '3', '4', null, 100)
> insert into foo values (3, ',1,11', ',1,5,6', 10, 100)
> insert into foo values (4, ',3,5', ',11', 10, null)
> (yes, the leading comma will randomly appear)
> unpleasant? yes. scheduled to be redesigned? yes. but for now, this is
> what i have to contend with.
> the problem i'm having is that there is another table with a very
> similar column, like so:
> create table foomatch (
> foomatchkey int primary key not null,
> foomatchintegerlist1 varchar(50) null
> foomatchintegerlist2 varchar(50) null,
> foomatchprice money null,
> foomatchsize int null
> )
> insert into foomatch values (1, ',2', ',4,5,6', 10, 100)
> insert into foomatch values (2, ',1,3,6', ',1', null, null)
> the goal of the select statement is to capture all of the rows in the
> table foo that "match" the values of a given single row in the foomatch
> table. the rules for matching are as follows:
> foomatch.foomatchprice = foo.fooprice AND
> foomatch.foomatchsize = foo.foosize AND
> (this is where it gets dicey for me)
> at least ONE of the integer values in foomatch.foomatchintegerlist1
> must occur in the foo.foointegerlist1 column AND
> at least ONE of the integer values in foomatch.foomatchintegerlist2
> must occur in the foo.foointegerlist1 column
> where foomatch.foomatchkey = 1 (for example)
> i have a user defined function that can turn a comma separated string
> value into a single column table. i mention this in case building
> tables of the values will make this easier / possible (perhaps with
> relational math?)
> thanks in advance for any help, and just let me know if you need
> clarification,
> jason
>|||thanks for the reply Jose.
i spent some time looking at string manipulation approaches, i'm not
sure string manipulation will do the trick here. even if we boiled it
down to a single comparison, how would you use string manipulation to
answer the question are any of the comma separated elements in ',1,2,3'
also in the comma separated list ',3,4,5'? i've spent some time going
down this path, and it didn't yield anything close to sane results.
though if you can post something a little more specific, i'd be happy
to entertain the notion.
and yes, my explanations are rarely brief. this isn't even close to one
of my longer ones :)|||If you use tables or table valued user defined functions for the integer
lists it is reasonably straightforward:
Assuming there are tables/udfs foolist1 (fookey, foointeger1) ,
foomatchlist1 (foomatchkey, foomatchinteger1) and foomatchlist2
(foomatchkey, foomatchinteger2)
SELECT f.<column list>
FROM foo f
INNER JOIN foomatch fm
ON fm.foomatchprice = f.fooprice
AND fm.foomatchsize = f.foosize
WHERE EXISTS
(
SELECT NULL FROM foolist1 fl1
INNER JOIN foomatchlist1 fml1
ON fl1.foointeger1 = fml1.foomatchinteger1
WHERE fl1.fookey = f.fookey AND fml1.foomatchkey = fm.foomatchkey
)
AND EXISTS
(
SELECT NULL FROM foolist1 fl1
INNER JOIN foomatchlist2 fml2
ON fl1.foointeger1 = fml2.foomatchinteger2
WHERE fl1.fookey = f.fookey AND fml2.foomatchkey = fm.foomatchkey
)
Jacco Schalkwijk
SQL Server MVP
"jason" <iaesun@.yahoo.com> wrote in message
news:1128432811.427135.37460@.g44g2000cwa.googlegroups.com...
> through no fault of my own, there exists a table with varchar(50)
> column, the values of which are comma separated integers. something
> like so:
> create table foo (
> fookey int primary key not null,
> foointegerlist1 varchar(50) null,
> foointegerlist2 varchar(50) null,
> fooprice money null,
> foosize int null
> )
> insert into foo values (1, ',2,3', '1', 10, 100)
> insert into foo values (2, '3', '4', null, 100)
> insert into foo values (3, ',1,11', ',1,5,6', 10, 100)
> insert into foo values (4, ',3,5', ',11', 10, null)
> (yes, the leading comma will randomly appear)
> unpleasant? yes. scheduled to be redesigned? yes. but for now, this is
> what i have to contend with.
> the problem i'm having is that there is another table with a very
> similar column, like so:
> create table foomatch (
> foomatchkey int primary key not null,
> foomatchintegerlist1 varchar(50) null
> foomatchintegerlist2 varchar(50) null,
> foomatchprice money null,
> foomatchsize int null
> )
> insert into foomatch values (1, ',2', ',4,5,6', 10, 100)
> insert into foomatch values (2, ',1,3,6', ',1', null, null)
> the goal of the select statement is to capture all of the rows in the
> table foo that "match" the values of a given single row in the foomatch
> table. the rules for matching are as follows:
> foomatch.foomatchprice = foo.fooprice AND
> foomatch.foomatchsize = foo.foosize AND
> (this is where it gets dicey for me)
> at least ONE of the integer values in foomatch.foomatchintegerlist1
> must occur in the foo.foointegerlist1 column AND
> at least ONE of the integer values in foomatch.foomatchintegerlist2
> must occur in the foo.foointegerlist1 column
> where foomatch.foomatchkey = 1 (for example)
> i have a user defined function that can turn a comma separated string
> value into a single column table. i mention this in case building
> tables of the values will make this easier / possible (perhaps with
> relational math?)
> thanks in advance for any help, and just let me know if you need
> clarification,
> jason
>|||ahh! i think i see the solution here. yes, i think i can modify my
udf's slightly to make this work. i will give that a shot.
thanks very much
jason
Complicated question about update procedures
My problem is that we need a method of updating the database without messing the data, or crashing the website.
I am sure this is a common problem with a number of solutions. Couldanyone please direct me to a good article on the best practices forupdating databases like this?
What do you mean by updating the database? Just inserting records o chaging its structure?
|||Anything. Inserting records is not a problem. It is changing the structure which is.
When I am developing, I dont want to be working on the live database.
But if I copy the database and edit the copy, what happens to any new data on the live database?
Hope that is not confusing.
|||When you make updates to the structure of the database you should consider whether it affects the behaviour of the application or not. If it doesn′t you can make the update at anytime (But it will be better to schedule it when there is no heavy traffic). If it affects the application, the update should be accompanied with an update in the application. In this case you should schedule a maintainance stop (obviously the users should be adviced with anticipation), and use that time to update everything, the application, the database, configurations, etc. I also work for a huge company with a lot of servers, databases and web applications running, and this is the way we behave.
|||
I was just wondering what the best approach to this kind of thing is.
For example, lets say I have version 1.0 of an application with a db backend. Now, when I start creating version 2, the application and db will change. Do I :
1. Edit the live db making extra care that version 1.0 is not affected by the changes. This has its obvious problems - one mistake and the whole application goes down.
2. Create a copy of the db, edit that, and then link that in with version 2 when it is ready. The problem with this is that, between the time ot copying the db and releasing version 2.0, the users are still using version 1.0 of the db. I would have to then copy that over. This isnt a problem with minor changes, but it is when I start changing/creating keys and constraints (especially in sql server).
So I was wondering what the industry works around creating the next version of software without corrupting the current version.
I know there is no right answer - it depends on the situation. But any guidence would be appriciated.
jagdipa wrote:
I know there is no right answer - it depends onthe situation. But any guidence would be appriciated.
I don't know that I agree with that statement. I think there is aright answer. It is called the Development, Staging, Productionmodel (DSP). The Staging database starts out as a mirror image ofthe Production database. Update scripts are run and tested on theStaging database until the consistent desiredresult is reached, with the Staging database being restored with abackup of theProduction database before each cycle of tests. This way, whenyou are ready to go live with your changes, you simple run the updatescripts that have been tested and perfected on the Staging databaseagainst your Production database.
Check out these links:
The Development, Staging, and Production Model
Setting up a DSP Environment -- look especially at the Managing Database Development section, and the Staging Environment section
|||Brilliant. Exactly what I was looking for.
I am just wondering if DSP is a standard method the industry uses, and are there other methods applied to this problem?
Again, thank you for the guidance
Jagdip
|||Just wondering if you have any more links about DSP?
|||Hi Jagdip, I was hoping someone else might chime in. I have noidea if the DSP approach is the industry standard, but it's the methodI've come to employ as a best practice for myself (in ideal situationsat least, sometimes some of the steps have been shortcut) and it is theway I've noticed some of my peers have worked. I've only recentlypicked up on the term "DSP" to be honest. When I read thedescription of the acronym I said to myself, "oh, I didn't know therewas a term appplied to this approach".
I just Googled a bit more and came up with this, which uses the DSP approach without using the term:
Migration to Production
I don't have many further resources for you, I'm afraid. The keyis to make your rollout to production consistently repeatable in yourstaging environment. This way when you go live you have minimizedyour risks as much as possible. I can't imagine an approach thatwould be better.
|||The only real problem we have is with updating the database. Writtingthe SQL scripts and saving then is a great way of keeping documentationon DB updates as well as keeping the existing data. Up until now, mycolleage has been working on the live database!!!!
I have had a word with him and he likes it. So thank you for theadvice. I'm in the process of writting and testing a procedure usingDSP, and I will have a look at the other article you gave me.
I guess the only real problem I have with DSP is that it will reallyslow down our RAD ideal. But the boss asked for something like this, sohe's going to have to live with it :-)
Complicated Query with Subs for Grand Total
I'm trying to get the syntax right below. Know that what I'm trying to do is correct (I don't want to explain why or the entire thing but just need help with correcting the syntax issues on the join and stuff:
Errors:
Msg 156, Level 15, State 1, Procedure IT_Get_ProjFee_GT, Line 205
Incorrect syntax near the keyword 'INNER'.
Msg 156, Level 15, State 1, Procedure IT_Get_ProjFee_GT, Line 213
Incorrect syntax near the keyword 'as'.
Msg 170, Level 15, State 1, Procedure IT_Get_ProjFee_GT, Line 219
Line 219: Incorrect syntax near 'branch'.
Msg 170, Level 15, State 1, Procedure IT_Get_ProjFee_GT, Line 219
Line 219: Incorrect syntax near ')'.
Msg 170, Level 15, State 1, Procedure IT_Get_ProjFee_GT, Line 221
Line 221: Incorrect syntax near ')'.
Select @.InHouse2 = SUM(InHouse2)
FROM
(Select SUM (CCsNewTable.SumOldCCs) * CASE WHEN FeeSchedule = 0 THEN
1
WHEN FeeSchedule = 1 THEN
FeeSchedule / 100
ELSE
FeeSchedule / 100
END AS InHouse2
FROM DC
INNER JOIN
( Select Company, FeeSchedule, SUM(OldCCs) SumOldCCs
INNER JOIN
(Select CC AS OldCCs from DC d
WHERE d.EnteredDate BETWEEN DATEADD(DAY, -DATEPART(DAY, @.today) + 1, @.today) AND DATEADD(DAY, -DATEPART(DAY, @.today), DATEADD(MONTH, 1, @.today)) AND d.EnteredDate IS NOT NULL
AND Type = 'CC'
AND ((branch = '00002' and customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 1) )
OR (customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 0) ))
AND pdc_OnHold IS NULL
GROUP BY CompanyNumber
) as CCsNewTable ON CompanyNumber = CCsNewTable.CompanyNumber
) as InHouse2Table
WHERE branch='00002'
AND Type = 'In-House'
AND ((branch = '00002' and customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 1))
OR (customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 0)))
)
Also tried adding aliases to distinguish the difference between DC and DC with d and dd
Select @.InHouse2 = SUM(InHouse2)
FROM
(Select SUM (CCsNewTable.SumOldCCs) * CASE WHEN FeeSchedule = 0 THEN
1
WHEN FeeSchedule = 1 THEN
FeeSchedule / 100
ELSE
FeeSchedule / 100
END AS InHouse2
FROM DCR d
INNER JOIN
( Select Company, FeeSchedule, SUM(OldCCs) SumOldCCs
INNER JOIN
(Select CC AS OldCCs from DCR dd
WHERE dd.EnteredDate BETWEEN DATEADD(DAY, -DATEPART(DAY, @.today) + 1, @.today) AND DATEADD(DAY, -DATEPART(DAY, @.today), DATEADD(MONTH, 1, @.today)) AND dd.EnteredDate IS NOT NULL
AND dd.Type = 'CC'
AND ((dd.branch = '00002' and dd.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 1) )
OR (dd.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 0) ))
AND dd.pdc_OnHold IS NULL
GROUP BY dd.CompanyNumber
) as CCsNewTable ON d.CompanyNumber = CCsNewTable.CompanyNumber
) as InHouse2Table
WHERE d.branch='00002'
AND d.Type = 'In-House'
AND ((d.branch = '00002' and d.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 1))
OR (d.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 0)))
)
|||You need to specify the JOIN conditions wiht your ON statement after the end of the subquery you are joining to, as I did in the part of the sub query:
as CCsNewTable ON CompanyNumber = CCsNewTable.CompanyNumber
HTH
|||
My aliases and other stuff are still screwed up...need some help on this one...I can't see it:
DECLARE @.today DATETIME,
@.datefirst datetime,
@.Posted money,
@.GrossGoal money,
@.OldPDCs money,
@.NewPDCs money,
@.OldCCs money,
@.NewCCs money,
@.InHouse1 money,
@.InHouse2 money,
@.Var1 money
SET @.today = CONVERT(CHAR(8), GETDATE(), 112) --'Jun 26 2005'
SET @.datefirst = @.@.DATEFIRST
Select @.InHouse2 = SUM(inhouse1table.InHouse2)
FROM
(Select SUM (InHouse2Table.InHouse2) * CASE WHEN FeeSchedule = 0 THEN
1
WHEN FeeSchedule = 1 THEN
FeeSchedule / 100
ELSE
FeeSchedule / 100
END AS InHouse2
FROM DC d
INNER JOIN
( Select branch, Type, CustomerNumber, CustomerName, SUM(OldCCs) * FeeSchedule as InHouse2
FROM DC ddd
INNER JOIN
(Select CustomerNumber, CC AS OldCCs from DC dd
WHERE dd.EnteredDate BETWEEN DATEADD(DAY, -DATEPART(DAY, @.today) + 1, @.today) AND DATEADD(DAY, -DATEPART(DAY, @.today), DATEADD(MONTH, 1, @.today)) AND dd.EnteredDate IS NOT NULL
AND dd.Type = 'CC'
AND ((dd.branch = '00002' and dd.CustomerNumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 1) )
OR (dd.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 0)))
AND dd.pdc_OnHold IS NULL
GROUP BY dd.CustomerNumber
)as CCsNewTable ON CompanyNumber = CCsNewTable.CompanyNumber
) as InHouse2Table on d.CustomerNumber = inhouse2table.CustomerNumber
WHERE d.branch='00002'
AND d.Type = 'In-House'
AND ((d.branch = '00002' and d.CustomerNumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 1))
OR (d.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 0)))
) as inhouse1table
|||
Please check out another post here which explains what I'm doing which was one step before this post:
http://www.experts-exchange.com/Databases/Microsoft_SQL_Server/Q_21753502.html
|||Is this a college assignment or something? Wh are you asking the same questions as dba123? If its for school, I cannot help you.|||are you out of your mind? does this look like a college assignement? something this complicated? What do you mean same questions...this is not the same. Is this too complicated for you to help me with? This is Grand Total that I have to mimic from a crazy excel spreadsheet from our finance dept....|||this is a complete different problem than you saw from dba123...if you read you'll realize this. Just check this out, OK then come back with some useful replies please:
http://www.experts-exchange.com/Databases/Microsoft_SQL_Server/Q_21753502.html
|||that's ok pal, I fixed it...
DECLARE @.today DATETIME,
@.datefirst datetime,
@.Posted money,
@.GrossGoal money,
@.OldPDCs money,
@.NewPDCs money,
@.OldCCs money,
@.NewCCs money,
@.InHouse1 money,
@.InHouse2 money,
@.Var1 money
SET @.today = CONVERT(CHAR(8), GETDATE(), 112) --'Jun 26 2005'
SET @.datefirst = @.@.DATEFIRST
Select @.InHouse2 = SUM(InHouse2)
FROM
(Select CCsOldTable.SumOldCCs * CASE WHEN d1.FeeSchedule = 0 THEN
1
WHEN d1.FeeSchedule = 1 THEN
(d1.FeeSchedule / 100)
ELSE
(FeeSchedule / 100)
END AS InHouse2
FROM DCR d1
INNER JOIN
(Select d2.CustomerNumber, SUM(CCsQuery.OldCCs) AS SumOldCCs
FROM DCR d2
INNER JOIN
-- NewCCs Query
(Select CustomerNumber, CC AS OldCCs
FROM DCR d3
WHERE d3.EnteredDate NOT BETWEEN DATEADD(DAY, -DATEPART(DAY, @.today) + 1, @.today) AND DATEADD(DAY, -DATEPART(DAY, @.today), DATEADD(MONTH, 1, @.today))
AND d3.Type = 'CC'
AND ((d3.branch = '00002' and d3.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 1))
OR (d3.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 0)))
AND d3.dc_OnHoldDate IS NULL
GROUP BY d3.CustomerNumber, d3.CC)as CCsQuery on CCsQuery.CustomerNumber = d2.CustomerNumber
GROUP BY d2.CustomerNumber
) as CCsOldTable ON d1.CustomerNumber = CCsOldTable.CustomerNumber
GROUP BY d1.CustomerNumber, CCsOldTable.SumOldCCs, d1.FeeSchedule
) as z
Select @.InHouse2
|||Sorry, did not mean to offend you, I was just wondering why you are using the same tables and queries. Hey, some college courses can get complicated now
Hope I was some help. Btw, you would probably be better (and quicker) to use a single join with an OR here instead of using IN, which is slow:
AND ((d3.branch = '00002' and d3.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 1))
OR (d3.customernumber IN (select CustomerNumber from CustomersAZ where CheckBranch = 0)))
thanks, sorry, yea, I was a bit irritated but that's cool.
Can you help me with your explanation ion using the single join with OR instead of IN ?
|||I figured it out....|||Sorry, that was the last thing I posted before logging off.