Showing posts with label row. Show all posts
Showing posts with label row. Show all posts

Monday, March 26, 2012

How to flag a row and allow max one row flagged in the table.

Hi,

I am new to SQL.

which is the best way to flag a row?

Create a bit column IsFlagged?

Additionally, I want to create a table-level constraint that allows max 1 row flagged true in the whole table. I can't nest a select expression in the CREATE TABLE statement CONSTRAINT clause that counts flagged rows.

So how do I do this?

Appreciate the help.

you can do something like this -

create table FlaggableDomain(ID int unique not null, Name sysname primary key not null)

populated something like this

ID DomainName
1 'person'
2 'place'
3 'thing'

track your flags with this -

create table FlaggedDomain (ItemID int not null, DomainID int not null, primary key (ItemID, DomainID))

to flag a row Person row -


insert into FlaggedDomain (ItemID, DomainId)
select person.id, domain.ID from
person
where name = 'SOME NAME' and
FlaggableDomain.DomainName = 'person'

to clear -

delete from FlaggedDomain where DomainId in
( select idFlaggableDomain
from FlaggableDomain
where DomainName = 'person')

to get flagged person -

select person.*
from person p inner join FlaggedDomain f
on p.id = f.ItemID

|||

Thanks for taking the time Blair,

Let me summarize what I made out of your reply:

1.Create a table of flags(FlaggableDomain)
2. Make a linking table(FlaggedDomain) linking flags with any other table(person), whose rows I want to flag.
3. By having a composite primary key for the linking table(FlaggableDomain) you ensure the person table can only have one row that has the flag 'person'.

This definitely is a solution, and probably the most professional one. However, I now face having to do 2 extra tables whenever I want to implement flagging logic, or have a central depository of many dissimilar flags and always having to join to this depository to be able to use the flags. In the former a table bloat, in the latter clunky code. Not quite like an enumeration in vb/c# which groups constants,hopefully, logically, depending on the author :).

There is one nice feature about your way, that is in a table that can have mixed rows of things/persons/places, more than one type of flag can be stored in the same column. Thus I can make sure max 1 'thing', max 1 'place', and max 1 'person' rows exist in that mixed table. I don't have that need now but it is a neat way.

A not so nice feature: not just any table's rows can be flagged this way. Only tables which have a simple(1 column), int primary key, which is the most common one but there are exceptions and they wouldn't be flaggable this way.

What about table level constraint?
I know I couldn't nest a select statement (and count) inside the constraint expression. Are there any options along those lines?

Forgive me if I am discovering the wheel out loud.

|||

However, I now face having to do 2 extra tables whenever I want to implement flagging logic, or have a central depository of many dissimilar flags and always having to join to this depository to be able to use the flags. In the former a table bloat, in the latter clunky code.

the code is not clunky at all. . . make views from simple select statements.

Always bear in mind that a primary key is a 'tuple' that defines a unique entity within a domain. Whereever possible, it should be a piece of data that you can look at without knowledge of the db and know what it is (natural key) . And as you noted, often times the primary key is compound and creating a foreign key reference would be unwieldly. When this is the case, the approach is to use what is called a unique, non-null "surrogate key" and propagate that value in foreign key references. You might find it useful to use uniqueidentifier fields. UniqueID's are cheap to create and generatate.

Tables are cheap to create too. Joins are cheap too.

Databases are geared to work with them - as long as the indexes are properly defined.

I am not sure if a table constraint is possible. Even if it were, it would take a total table scan to assure that the constraint we enforced.

google "Surrogate Key"

|||

I looked into surrogate keys and will definitely rethink doing composite keys in the future.

Learned a lot from you!

Thanks a bunch.

|||

cheers!

|||

Blair,

Can I milk you for a bit more advice?

Is this type of flagging appropriate to implement data versioning?

say a sports league. A player can be active in just one team, but I want to keep prior team membership in a foreign key table. Only one of those team memberships would be flagged 'current' as we discussed. The rest are just stale versions, but I want to keep that history data.

When the player moves to another team, it would have to be a transaction removing the flag from the old team, and flagging the new one?

Is this the right way of doing versioning?

Carl

|||

I don't know if versioning is the right term. I would consider this a Transaction. Note: i am using this in the natural sense of the word, not database concurrency management.

Legend: Table(KeyFields, SurrogateKeyField, SupplementalField), with foreign keys marked by Field -> Table(KeyField) and I am using integer ID's for brevity. ID data type is irrelevant with the condition that it is easily generated.

First, Active Status on a team would be enforced by Roster(PlayerID, TeamID)

Next, I would have a table TransactionType(TransID, TransName, TransAbbr)

this would be populated by something like:

1, Draft, DR
2, Free-Agent, FA
3, Injured, IR
4, Disabled, DL
5, Trade Out, TO
6, Trade In, TI
7, Released, RE

I would create a PlayerHistory table to track the status changes of players -

PlayerHistory(HistoryID, PlayerID -> Player(PlayerID), TeamID -> Team(TeamID), TransID -> TransactionType(TransID), DateOfEntry , RelatedHistory -> PlayerHistory(HistoryID))

Note the self reference on player history, this would be used for trades - Each trade out has a related trade in. For all other entries in a players history, the related history would be null.

Say team1 traded player 1 to team 2 for player 2 on 1/1/2006 -

1, 1, 1, 5, 1/1/2006, 2
2, 1, 2, 6, 1/1/2006, 1
3, 2, 2, 5, 1/1/2006, 4
4, 2.,1, 6, 1/1/2006, 3

This could get more elaborate - TradeMaster (TradeID, AgreementDocument)

TradeHistory(TradeID, PlayerHistoryID -> PlayerHistory(HistoryID))

This could be used to track the Trade-Outs that were affected by the aggreement. From our example above:

TradeMaster might be:
1, "Team 1 will give Team 2 a first round draft pick next year"

And TradeHistory would simply be:
1, 1
1, 3

You could trigger off of TradeHistory to automatically insert PlayerHistory and update Roster

Now you might be thinking, as you said "Table Bloat." Tables and Disk-Space is cheap. What is expensive is processor time! You want to minimize the amount of clock cycles that need to be executed, both in the client application or the database server. Inserting or changing data that is indexed or constrained is expensive. Get it in the table in a way that minimizes changes to indexed fields. If you have to manipulate data that is indexed or constrained, you want to do it once, if possible.

Finally, it only takes the execution of 3 instructions to retrieve a set of rows based on index. Indexes on bit fields give no benefit.

Other things to google "Normal-Form" and "DKNF" - Note: DKNF is an ideal, strive for it, but it is not always feasible.

Database Theory is as much an art as it is a science. People get PhD's in Database Therory, but there is no "Right" model for a given Domain Set, but there are models that are more proper than others. I liken it to the game othello, "A minute to learn, a lifetime to master."

Oh yeah! Don't forget to eat and sleep! (Yeah, as if you will be able to sleep once you get started thinking about your data model)

Don't get me started on the term "Normal" and it roots in mathematics.

Good luck and have fun.

|||

Thanks Blair,

You answered even my next couple of questions.

Good advice re the sleep bit!

Cheers

Wednesday, March 21, 2012

How to find the Row Number Transformation

I need help on how to find the Row Number Transformation,

I have followed this link http://www.sqlis.com/default.aspx?93

but I cannot find the Trash Destination. Could someone please tell me where I can download it?

Thanks

thanks|||

http://www.sqlis.com/default.aspx?56

|||You have posted the link to the Trash Destination page, just scroll down for the link to the download, Version 1.0.1.1.

Monday, March 19, 2012

How to find row value not present

Hi All,
I have table with 2 cols 1)ObjectName 2)Owner (omlitted other cols for
simplicity)
ObjectName Owner
obj1 own1
obj1 own2
obj2 own1
obj2 own2
obj3 own1
obj4 own2
if ObjectName is present for own1 It should also be there for own2 &
other way around if ObjectName is present for own2 it should also be
there for own1. I want to find out rows which does not meet such
criteria. like in above example last 2 rows for obj3 & obj4.
As obj3 is present for only own1 & obj4 is present for own2 only.
Could any one guide me how to go about it?
Thanks in advance for help
VinodVinod
CREATE TABLE dbo.Stuffs (
obj_name VARCHAR(4) NOT NULL
,owner VARCHAR(4) NOT NULL
CHECK (owner IN ('own1', 'own2'))
,PRIMARY KEY (obj_name, owner)
);
INSERT INTO Stuffs VALUES('obj1', 'own1');
INSERT INTO Stuffs VALUES('obj1', 'own2');
INSERT INTO Stuffs VALUES('obj2', 'own1');
INSERT INTO Stuffs VALUES('obj2', 'own2');
INSERT INTO Stuffs VALUES('obj3', 'own1');
INSERT INTO Stuffs VALUES('obj4', 'own2');
SELECT obj_name FROM Stuffs
GROUP BY obj_name
HAVING COUNT(owner) <> 2
;
Joe|||create table foo (objectname varchar(5), owner varchar(5))
insert into foo values ('obj1','own1')
insert into foo values ('obj1','own2')
insert into foo values ('obj2','own1')
insert into foo values ('obj2','own2')
insert into foo values ('obj3','own1')
insert into foo values ('obj4','own2')
insert into foo values ('obj4','own3')
insert into foo values ('obj4','own3')
select every.*
from
(select obj.objectname, own.owner from (select distinct objectname from foo)
obj
cross join (select distinct owner from foo) own ) every
where objectname+owner not in (select objectname+owner from foo)
"vinod" <vinod.patil1@.gmail.com> wrote in message
news:1132180115.463350.278900@.g44g2000cwa.googlegroups.com...
> Hi All,
> I have table with 2 cols 1)ObjectName 2)Owner (omlitted other cols for
> simplicity)
> ObjectName Owner
> obj1 own1
> obj1 own2
> obj2 own1
> obj2 own2
> obj3 own1
> obj4 own2
> if ObjectName is present for own1 It should also be there for own2 &
> other way around if ObjectName is present for own2 it should also be
> there for own1. I want to find out rows which does not meet such
> criteria. like in above example last 2 rows for obj3 & obj4.
> As obj3 is present for only own1 & obj4 is present for own2 only.
> Could any one guide me how to go about it?
> Thanks in advance for help
> Vinod
>|||Why do you think that EVERY is a keyword in SQL?|||"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1132196174.489954.44330@.g14g2000cwa.googlegroups.com...
> Why do you think that EVERY is a keyword in SQL?
>
He doesn't think that. He thinks it's a table alias, because that
is what it is being used for.
Sincerely,
Chris O.

Monday, March 12, 2012

How to find out wether a row has been replicated?

Dear ppl,

In Merge Replication SQL Server2005, what is the easiest way of finding out wether a row on the publisher database has ever been replicated to subscribers?

Regards

Nabeel-

The procedure below should get you started on being able to tell if a row has been sent to a subscriber, all you need to do is provide the rowguid and publication name.

use <PUB_DB_NAME>

go

create procedure ASubHasIt(@.pubname sysname, @.row uniqueidentifier)

as

declare @.tablenick int

declare @.maxsentgen int

select @.maxsentgen = max(sentgen), @.tablenick = max(nickname) from (sysmergesubscriptions sms join sysmergepublications smp on sms.pubid = smp.pubid) join sysmergearticles sma on sma.pubid=smp.pubid where smp.name='PubName' and sms.sentgen IS NOT NULL

if exists (select * from MSmerge_genhistory gh join MSmerge_contents mc on mc.generation = gh.generation where gh.generation > @.maxsentgen and mc.rowguid = @.row)

begin

print 'Row ' + CONVERT(nvarchar(max), @.row) + ' has NOT been sent to a subscriber'

end

else

begin

print 'Row ' + CONVERT(nvarchar(max), @.row) + ' has been sent to a subscriber'

end

go

Example:

exec ASubHasIt @.pubname='PubName', @.row='8B348C04-B3A9-DB11-AEA6-000BDBD0506C'

Hope this helps!

-Phil Piwonka

|||excellent...cheers mate :)

How to find out row that was just inserted?

hi folks,
Is it possible to find out the row which was just inserted in a table? I am creating a trigger and i m trying to access the row which was just inserted into the table. Any suggestions? Thanks a million!
GayathriWithin a trigger you can access the newly inserted/updated/deleted fields by referencing virtual tables named:
"inserted" - holds new and updated records
"deleted" - holds deleted records

You just reference these tables as you would any permanent table:

select count(*)
from YOURTABLE
inner join INSERTED
on YOURTABLE.PRIMARYKEY = INSERTED.PRIMARYKEY

blindman|||My code is as follows

DECLARE job_number_cursor CURSOR FOR
SELECT JobNumber
FROM asiapac702_test.dbo.tblCustServiceHistoryHdr
where JobNumber = Inserted.JobNumber
OPEN job_number_cursor
FETCH NEXT FROM job_number_cursor INTO
@.job_number

CLOSE job_number_cursor
DEALLOCATE job_number_cursor

But i get an error saying
"The column prefix 'Inserted' does not match with a table name or alias name used in the query. "

Is there any other syntax that i am missing?|||try this...

DECLARE job_number_cursor CURSOR FOR
SELECT JobNumber
FROM asiapac702_test.dbo.tblCustServiceHistoryHdr
where JobNumber = (select Inserted.JobNumber from inserted)
OPEN job_number_cursor
FETCH NEXT FROM job_number_cursor INTO
@.job_number

CLOSE job_number_cursor
DEALLOCATE job_number_cursor|||Did modify to the code below but again it says "Invalid Object Name 'Inserted':(

Originally posted by rokslide
try this...

DECLARE job_number_cursor CURSOR FOR
SELECT JobNumber
FROM asiapac702_test.dbo.tblCustServiceHistoryHdr
where JobNumber = (select Inserted.JobNumber from inserted)
OPEN job_number_cursor
FETCH NEXT FROM job_number_cursor INTO
@.job_number

CLOSE job_number_cursor
DEALLOCATE job_number_cursor|||this is the suggestion from MS...

CREATE TRIGGER Trigger1 ON dbo.TableA
FOR INSERT
AS
DECLARE @.var1 INT
DECLARE @.VarA int

SELECT @.VarA = SELECT col2 FROM inserted
DECLARE cursor1 CURSOR FOR
SELECT col1
FROM TableB
WHERE col1 = @.VarA

OPEN cursor1
FETCH NEXT FROM cursor1 INTO @.var1

CLOSE cursor1
DEALLOCATE cursor1
GO|||So modifying it for your purposes...

DECLARE @.SearchJobNumber int
DECLARE @.job_number int
SELECT @.JobNumber = SELECT JobNumber from inserted

DECLARE job_number_cursor CURSOR FOR
SELECT JobNumber
FROM asiapac702_test.dbo.tblCustServiceHistoryHdr
where JobNumber = @.JobNumber
OPEN job_number_cursor
FETCH NEXT FROM job_number_cursor INTO
@.job_number

CLOSE job_number_cursor
DEALLOCATE job_number_cursor|||Here is how to rewrite your original statement to avoid the error you got:

DECLARE job_number_cursor CURSOR FOR SELECT JobNumber FROM Inserted
OPEN job_number_cursor
FETCH NEXT FROM job_number_cursor INTO
@.job_number

CLOSE job_number_cursor
DEALLOCATE job_number_cursor

The big question is why you are putting a cursor in a trigger. This is the database equivalent of pouring sewage into your gas tank.

blindman|||Cursor in trigger? Do not think it is good idea...|||I got the impression that things are getting on the wrong path. Summa summarum, the answer for your original question is given by Blindman in his first post:

select count(*)
from YOURTABLE
inner join INSERTED
on YOURTABLE.PRIMARYKEY = INSERTED.PRIMARYKEY

But this should be used in the trigger written on the table which you are interested in. Got the picture?
You probably get the error "Invalid Object Name 'Inserted'" because you are not using the code in the wright place.

Best regards!|||Can you not just use the @.@.IDENTITY property?

Or does this not work in a trigger?

Friday, March 9, 2012

How to find nth lowest value in a row

Morning all,
I have a table with 500+ fields of numeric data (a time series of values) I
import from an external system. I need to find the 5th and 6th lowest values
in a given row to perform some calculations.
I currently do this by transposing the data row ie turning the row into a
column sorting it and then using row_num to get the 5th and 6th lowest
values. This transpose is a real bottleneck on my process.
Does anyone have any alternatives to my method ? All suggestions gratefully
received.
Thanks
WOn Thu, 16 Aug 2007 17:56:35 -0700, willcas wrote:
>Morning all,
>I have a table with 500+ fields of numeric data (a time series of values) I
>import from an external system. I need to find the 5th and 6th lowest values
>in a given row to perform some calculations.
>I currently do this by transposing the data row ie turning the row into a
>column sorting it and then using row_num to get the 5th and 6th lowest
>values. This transpose is a real bottleneck on my process.
>Does anyone have any alternatives to my method ? All suggestions gratefully
>received.
Hi W,
Perhaps you could transpose the data during the import and store it in a
more relational way?
The only other alternative would be a really very nasty (and long!) CASE
epxression that I won't even begin to think about <shudder>.
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||"willcas" <willcas@.discussions.microsoft.com> wrote in message
news:6658592C-0F0A-45C6-BB9C-DFDDF0263FF2@.microsoft.com...
> Morning all,
> I have a table with 500+ fields of numeric data (a time series of values)
> I
> import from an external system. I need to find the 5th and 6th lowest
> values
> in a given row to perform some calculations.
> I currently do this by transposing the data row ie turning the row into a
> column sorting it and then using row_num to get the 5th and 6th lowest
> values. This transpose is a real bottleneck on my process.
> Does anyone have any alternatives to my method ? All suggestions
> gratefully
> received.
> Thanks
> W
I would treat this as a staging table and transform the data to a properly
normalized model. Then write your query against that new model.
Perhaps better still, do the transformation before the load (using
Integration Services for example).
--
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
--|||Can't you use unpivot for the transposition?
"willcas" <willcas@.discussions.microsoft.com> wrote in message
news:6658592C-0F0A-45C6-BB9C-DFDDF0263FF2@.microsoft.com...
> Morning all,
> I have a table with 500+ fields of numeric data (a time series of values)
> I
> import from an external system. I need to find the 5th and 6th lowest
> values
> in a given row to perform some calculations.
> I currently do this by transposing the data row ie turning the row into a
> column sorting it and then using row_num to get the 5th and 6th lowest
> values. This transpose is a real bottleneck on my process.
> Does anyone have any alternatives to my method ? All suggestions
> gratefully
> received.
> Thanks
> W

Wednesday, March 7, 2012

How to find max from a table by row

I have a Product table with the columns

AcctNum
ProdCode
InvoiceDate

I can have multiple rows for a given AcctNum:

123 A 01/01/2005
123 B 01/02/2005
123 C 01/03/2005
234 C 02/01/2004
345 A 01/01/2005
345 B 01/02/2005

I need the max(InvoiceDate) and if the max for a given AcctNum is a ProdCode
= B. So if the latest InvoiceDate is for a given AcctNum is B then return
that row.

123 B 01/02/2005
Would not be returned because the max Invoice date for AcctNum 123 is
ProdCode C.

345 B 01/02/2005
Would be returned because the max Invoice date for AcctNum 345 is ProdCode
B.

I can solve this using a cursor fairly easily by using a distinct AcctNum in
the cursor select and getting the max InvoiceDate for each AcctNum. This is
a costly and I'm looking for a solution using temp tables or a query to
handle this problem.

I hope I have made this clear enough (sorry if I was too verbose). Thanks in
advance for your help.

-pHi

Try

SELECT A.AcctNum, A.ProdCode, A.InvoiceDate
FROM MyAccts A
WHERE ProdCode = 'B'
AND NOT EXISTS ( SELECT 1 FROM MyAccts B WHERE A.AcctNum = B.AcctNum AND
B.InvoiceDate > A.InvoiceDate )

or

SELECT A.AcctNum, A.ProdCode, A.InvoiceDate
FROM MyAccts A
WHERE ProdCode = 'B'
AND A.InvoiceDate = ( SELECT MAX(B.InvoiceDate) FROM MyAccts B WHERE
A.AcctNum = B.AcctNum )

Also check out how to post DDL and example data at
http://www.aspfaq.com/etiquett*e.asp?id=5006 and
example data as insert statements http://vyaskn.tripod.com/code.*htm#inserts
It is also useful to post your current attempts at solving the problem.

John
"Pippen" <name@.notreal.add> wrote in message
news:O9GdnTvxA-1jPqHfRVn-iw@.comcast.com...
>I have a Product table with the columns
> AcctNum
> ProdCode
> InvoiceDate
> I can have multiple rows for a given AcctNum:
> 123 A 01/01/2005
> 123 B 01/02/2005
> 123 C 01/03/2005
> 234 C 02/01/2004
> 345 A 01/01/2005
> 345 B 01/02/2005
> I need the max(InvoiceDate) and if the max for a given AcctNum is a
> ProdCode = B. So if the latest InvoiceDate is for a given AcctNum is B
> then return that row.
> 123 B 01/02/2005
> Would not be returned because the max Invoice date for AcctNum 123 is
> ProdCode C.
> 345 B 01/02/2005
> Would be returned because the max Invoice date for AcctNum 345 is ProdCode
> B.
> I can solve this using a cursor fairly easily by using a distinct AcctNum
> in the cursor select and getting the max InvoiceDate for each AcctNum.
> This is a costly and I'm looking for a solution using temp tables or a
> query to handle this problem.
> I hope I have made this clear enough (sorry if I was too verbose). Thanks
> in advance for your help.
> -p
>|||"John Bell" <jbellnewsposts@.hotmail.com> wrote in message
news:423d73a3$0$32610$db0fefd9@.news.zen.co.uk...
> Hi
> Try
> SELECT A.AcctNum, A.ProdCode, A.InvoiceDate
> FROM MyAccts A
> WHERE ProdCode = 'B'
> AND NOT EXISTS ( SELECT 1 FROM MyAccts B WHERE A.AcctNum = B.AcctNum AND
> B.InvoiceDate > A.InvoiceDate )
> or
> SELECT A.AcctNum, A.ProdCode, A.InvoiceDate
> FROM MyAccts A
> WHERE ProdCode = 'B'
> AND A.InvoiceDate = ( SELECT MAX(B.InvoiceDate) FROM MyAccts B WHERE
> A.AcctNum = B.AcctNum )
> Also check out how to post DDL and example data at
> http://www.aspfaq.com/etiquett*e.asp?id=5006 and
> example data as insert statements
> http://vyaskn.tripod.com/code.*htm#inserts
> It is also useful to post your current attempts at solving the problem.
> John
> "Pippen" <name@.notreal.add> wrote in message
> news:O9GdnTvxA-1jPqHfRVn-iw@.comcast.com...
>>I have a Product table with the columns
>>
>> AcctNum
>> ProdCode
>> InvoiceDate
>>
>> I can have multiple rows for a given AcctNum:
>>
>> 123 A 01/01/2005
>> 123 B 01/02/2005
>> 123 C 01/03/2005
>> 234 C 02/01/2004
>> 345 A 01/01/2005
>> 345 B 01/02/2005
>>
>> I need the max(InvoiceDate) and if the max for a given AcctNum is a
>> ProdCode = B. So if the latest InvoiceDate is for a given AcctNum is B
>> then return that row.
>>
>> 123 B 01/02/2005
>> Would not be returned because the max Invoice date for AcctNum 123 is
>> ProdCode C.
>>
>> 345 B 01/02/2005
>> Would be returned because the max Invoice date for AcctNum 345 is
>> ProdCode B.
>>
>> I can solve this using a cursor fairly easily by using a distinct AcctNum
>> in the cursor select and getting the max InvoiceDate for each AcctNum.
>> This is a costly and I'm looking for a solution using temp tables or a
>> query to handle this problem.
>>
>> I hope I have made this clear enough (sorry if I was too verbose). Thanks
>> in advance for your help.
>>
>> -p
>
Thanks for the help.

-p

Friday, February 24, 2012

how to find conditions across rows (attendance)

Hello,
I need to find students that have 4 consecutive absences. When a
student is absent 4 times in a row, they can be dropped from the class.

My class attendance file contains each attendance by date and whether
they were present or not. When the student has 4 consecutive value 1
(absent) for a given session and a given class the are considered to be
dropped.
If I needed to know the total number of absences, I know I could group
and summarize, but this one has the consecutive twist.
Table:

CREATE TABLE "dbo"."clsatt"
("FULL_CLASS_ID" CHAR(15) NOT NULL,
"STUDENT_ID" CHAR(20) NULL,
"SESSION_ID" CHAR(10) NULL,
"MEETING" SMALLINT NOT NULL,
"PRESENT" CHAR(2) NOT NULL)
;
Present value of 1 is absent, value of 2 is present (3 means holiday)
Classes typically meet 12 times.
I would want something like
FULL_CLASS_ID, STUDENT_ID, SESSION_ID, 'Dropped'
as the output.

Notice in the example the first student was absent the last 4 meetings
The second student 5 absenses
and the third student was totally absent
In these three examples, they are flagged as dropped.
TIA
Rob
Inserts:

------------------------
insert into clsatt values ('BUS100','1675812194','200203',1,'2')
insert into clsatt values ('BUS100','1675812194','200203',2,'2')
insert into clsatt values ('BUS100','1675812194','200203',3,'2')
insert into clsatt values ('BUS100','1675812194','200203',4,'2')
insert into clsatt values ('BUS100','1675812194','200203',5,'2')
insert into clsatt values ('BUS100','1675812194','200203',6,'2')
insert into clsatt values ('BUS100','1675812194','200203',7,'2')
insert into clsatt values ('BUS100','1675812194','200203',8,'2')
insert into clsatt values ('BUS100','1675812194','200203',9,'1')
insert into clsatt values ('BUS100','1675812194','200203',10,'1')
insert into clsatt values ('BUS100','1675812194','200203',11,'1')
insert into clsatt values ('BUS100','1675812194','200203',12,'1')
insert into clsatt values ('BUS100','1712400537','200203',1,'2')
insert into clsatt values ('BUS100','1712400537','200203',2,'2')
insert into clsatt values ('BUS100','1712400537','200203',3,'2')
insert into clsatt values ('BUS100','1712400537','200203',4,'2')
insert into clsatt values ('BUS100','1712400537','200203',5,'2')
insert into clsatt values ('BUS100','1712400537','200203',6,'2')
insert into clsatt values ('BUS100','1712400537','200203',7,'2')
insert into clsatt values ('BUS100','1712400537','200203',8,'1')
insert into clsatt values ('BUS100','1712400537','200203',9,'1')
insert into clsatt values ('BUS100','1712400537','200203',10,'1')
insert into clsatt values ('BUS100','1712400537','200203',11,'1')
insert into clsatt values ('BUS100','1712400537','200203',12,'1')
insert into clsatt values ('BUS100','1801704805','200203',1,'1')
insert into clsatt values ('BUS100','1801704805','200203',2,'1')
insert into clsatt values ('BUS100','1801704805','200203',3,'1')
insert into clsatt values ('BUS100','1801704805','200203',4,'1')
insert into clsatt values ('BUS100','1801704805','200203',5,'1')
insert into clsatt values ('BUS100','1801704805','200203',6,'1')
insert into clsatt values ('BUS100','1801704805','200203',7,'1')
insert into clsatt values ('BUS100','1801704805','200203',8,'1')
insert into clsatt values ('BUS100','1801704805','200203',9,'1')
insert into clsatt values ('BUS100','1801704805','200203',10,'1')
insert into clsatt values ('BUS100','1801704805','200203',11,'1')
insert into clsatt values ('BUS100','1801704805','200203',12,'1')
insert into clsatt values ('BUS100','1922287588','200203',1,'1')
insert into clsatt values ('BUS100','1922287588','200203',2,'1')
insert into clsatt values ('BUS100','1922287588','200203',3,'2')
insert into clsatt values ('BUS100','1922287588','200203',4,'2')
insert into clsatt values ('BUS100','1922287588','200203',5,'2')
insert into clsatt values ('BUS100','1922287588','200203',6,'2')
insert into clsatt values ('BUS100','1922287588','200203',7,'2')
insert into clsatt values ('BUS100','1922287588','200203',8,'2')
insert into clsatt values ('BUS100','1922287588','200203',9,'2')
insert into clsatt values ('BUS100','1922287588','200203',10,'2')
insert into clsatt values ('BUS100','1922287588','200203',11,'1')
insert into clsatt values ('BUS100','1922287588','200203',12,'2')
insert into clsatt values ('BUS100','2188469657','200203',1,'1')
insert into clsatt values ('BUS100','2188469657','200203',2,'1')
insert into clsatt values ('BUS100','2188469657','200203',3,'2')
insert into clsatt values ('BUS100','2188469657','200203',4,'2')
insert into clsatt values ('BUS100','2188469657','200203',5,'2')
insert into clsatt values ('BUS100','2188469657','200203',6,'2')
insert into clsatt values ('BUS100','2188469657','200203',7,'2')
insert into clsatt values ('BUS100','2188469657','200203',8,'2')
insert into clsatt values ('BUS100','2188469657','200203',9,'1')
insert into clsatt values ('BUS100','2188469657','200203',10,'1')
insert into clsatt values ('BUS100','2188469657','200203',11,'1')
insert into clsatt values ('BUS100','2188469657','200203',12,'2')
insert into clsatt values ('BUS100','2515197431','200203',1,'1')
insert into clsatt values ('BUS100','2515197431','200203',2,'1')
insert into clsatt values ('BUS100','2515197431','200203',3,'2')
insert into clsatt values ('BUS100','2515197431','200203',4,'2')
insert into clsatt values ('BUS100','2515197431','200203',5,'1')
insert into clsatt values ('BUS100','2515197431','200203',6,'2')
insert into clsatt values ('BUS100','2515197431','200203',7,'2')
insert into clsatt values ('BUS100','2515197431','200203',8,'1')
insert into clsatt values ('BUS100','2515197431','200203',9,'2')
insert into clsatt values ('BUS100','2515197431','200203',10,'2')
insert into clsatt values ('BUS100','2515197431','200203',11,'1')
insert into clsatt values ('BUS100','2515197431','200203',12,'2')
select FULL_CLASS_ID,STUDENT_ID,SESSION_ID,'Dropped'
from (
select t1.FULL_CLASS_ID,
t1.STUDENT_ID,
t1.SESSION_ID,
t1.MEETING -
(select count(*) from clsatt t2
where t2.FULL_CLASS_ID=t1.FULL_CLASS_ID
and t2.STUDENT_ID=t1.STUDENT_ID
and t2.SESSION_ID=t1.SESSION_ID
and t2.MEETING<=t1.MEETING
and t2.PRESENT='1') as Rn
from clsatt t1
where t1.PRESENT='1') X
group by FULL_CLASS_ID,STUDENT_ID,SESSION_ID,Rn
having count(*)>= 4|||Mark,
Thanks much!
Rob|||I need to find students that have 4 consecutive absences. When a
student is absent 4 times in a row, they can be dropped from the class.

My class attendance file contains each attendance by date and whether
they were present or not. When the student has 4 consecutive value 1
(absent) for a given session and a given class the are considered to be
dropped.
If I needed to know the total number of absences, I know I could group
and summarize, but this one has the consecutive twist.
Table:

The tabel made no sense. NULL student ids of 20 characters in length?
Numeric attendance codes kept in CHAR(), you have no key? etc.

CREATE TABLE ClassAttendance
(class_name CHAR(15) NOT NULL,
student_id CHAR(20) NOT NULL,
session_id CHAR(10) NOT NULL,
meeting_nbr INTEGER NOT NULL,
attend_code INTEGER DEFAULT 1 NOT NULL
CHECK (attend_code IN (1,2,3)),
PRIMARY KEY (class_name, student_id, session_id, meeting_nbr));

Here is a shot using the new OLAP functions:

SELECT DISTINCT student_id, class_name, session_id
FROM (SELECT student_id, class_name, session_id,
SUM(attend_code)
OVER(PARTITION BY class_name, session_id
ORDER BY student_id, class_name, session_id
ROWS 4 PRECEDING)
FROM ClassAttendance
GROUP BY student_id, class_name, session_id)
AS X (student_id, class_name, session_id, last_four)
WHERE last_four = 4;|||thanks for your input Celko.

The table is only representative as to help me with the SQL, it is not
my student dimension as it is stored in my data warehouse.
The attendance code (PRESENT in my example) is an ID or attribute of
the attendance and not a fact. Therefore it is intended to be a char
type (or varchar). Summing on this field wont make sense from the
business. The only non-char type fields I keep are facts that can be
aggregated (tuition charges, payments and so forth).
Since this is a data warehouse intended to incorporate data from our
current operational systems as well as future currently unknown
systems, I need the flexibility that char provides. Another system
might have alpha-numeric student ID's.
I use DataManager from Cognos to build my warehouse, which has PK
information, so I have not defined in the database PKs (yet).
When I post for help, I don't expect to get exact SQL for my exact
problem; therefore I post what is representative of my problem. Also,
the solutions and ideas people post sometimes don't do what I need,
but provide me valuable knowledge to help solve future problems.
However in this case markc nailed it and I was able to solve my problem
and learn something new!
As for learning something new, I will try your example and see what it
does. Thanks for your input!
Thanks
Rob|||SQL Server 2005 doesn't support SUM()..OVER(ORDER BY..ROWS 4 PRECEDING)
However, you can do this

select FULL_CLASS_ID,STUDENT_ID,SESSION_ID,'Dropped'
from (
select FULL_CLASS_ID,
STUDENT_ID,
SESSION_ID,
MEETING - RANK() OVER(PARTITION BY
FULL_CLASS_ID,STUDENT_ID,SESSION_ID
ORDER BY MEETING) as Rn
from clsatt
where PRESENT='1') X
group by FULL_CLASS_ID,STUDENT_ID,SESSION_ID,Rn
having count(*)>= 4

Regards

Mark|||Anohter answer: Since there are only a few ranges, we can build an
auxiliary table and use it:

CREATE TABLE FourRanges
(start_session_nbr INTEGER NOT NULL,
end_session_nbr INTEGER NOT NULL,
CHECK (start_session_nbr < end_session_nbr));

INSERT INTO FourRanges VALUES (1, 4);
INSERT INTO FourRanges VALUES (2, 5);
INSERT INTO FourRanges VALUES (3, 6);
INSERT INTO FourRanges VALUES (4, 7);
..
INSERT INTO FourRanges VALUES (9, 12);

SELECT A1.course_name, A1.session_id, A1.student_id,
SUM(attend_code)
FROM ClassAttendance AS A1, FourRanges AS F
WHERE A1.session_nbr BETWEEN F.start_session_nbr
AND F.end_session_nbr
GROUP BY course_name, session_id, student_id
HAVING SUM(attend_code) = 4;

Sunday, February 19, 2012

how to find a simple quote in a row

Hi,
I have a table with a "description" row.
In this row I may have some simple quote (') character.
How can I select them ?
something like :
select * from myTable where description like %'%
thanksselect * from myTable where description like %''%

Use TWO single quotes. They are treated as one.|||don't forget the quotes around the pattern :)

... where description like '%''%'|||Other alternative is

select * from tableName where charindex('''',Colname)>0

How to find a perticular row?

Hi all,
I want to select last but one row in a table. I shouldn't use pk_id of the table ,because the entries in a table are jumbled.
I want the last but one row that as entered.
Thanks in advance
venkatHi vencat

This gets right to the nub of relational theory. Tables in an RDBMS are sets of data. Think of a Venn diagram - there is no order right? Just some "clouds" to represent sets. As such there is no such thing as last or first or last but one in a relational table. Order of insertion and physical order on disk is irrelevent. So - unless you have used some sort of timestamp for when you inserted the data (say a column with a default value of GETDATE()) or some other method of determining a logical order of the data then you cannot satisfy your requirement

HTH|||select top 1 * from yourtable order by newid()

;)|||select top 1 * from yourtable order by newid()

;)

doesn't that just grab a random row?|||Originally Posted by jezemine
select top 1 * from yourtable order by newid()
this is definitely not a correct way to select last but one row. I don't think it is not possbile if you don't have timestamp or identity or smiliar column.|||doesn't that just grab a random row?
this is definitely not a correct way to select last but one row. I don't think it is not possbile if you don't have timestamp or identity or smiliar column.Did you guys miss the wink? And Jesse's increasing ratio of sarcy to serious posts? ;)

Anyway - everyone knows it is:
select top 1 * from yourtable order by newid() DESC|||select top 1 *
from ( select t.*, newid() as random_number
from yourtable as t ) as inline_view
order by random_number desc|||SELECT TOP 1 A_SQL99_compliant_derived_table.*
FROM --A SQL99 compliant derived table
(SELECT *
, rn = row_number() OVER (ORDER BY newid() DESC)
FROM meTable) AS A_SQL99_compliant_derived_table
WHERE rn = 1
My - we are a witty bunch.

I said witty :)|||very nice, and very elegant, too

but shouldn't it be An_SQL99_compliant_derived_table|||very nice, and very elegant, tooThanks :cool: I like to write tight, elegent code to meet the requirements.

but shouldn't it be An_SQL99_compliant_derived_tableI'm an old skooler Rudy - it is pronounced SEQUEL in the flump household.:)|||ok, ok, i feel bad now. ;)

this will give you the second to last row, where "last" is determined by ordering the "item" column alphabetically.

declare @.t table (item varchar(10))

insert into @.t
select 'aaa' union all
select 'bbb' union all
select 'ccc' union all
select 'ddd' union all
select 'eee' union all
select 'fff'

select top 1 a.* from
(select top 2 * from @.t order by item desc) a
order by item asc|||select top 1 * from yourtable order by newid()

;)

-It is retrieving only row 1 based on the primary key of the table.I am not willing to use primary key.

Thanks|||Ok..Guys I tested all your posts.but no one retrieving the last but row.But some of them returning last row depending on primary key of the table ,that i can achieve easily .but i don't want to use primary key...

when i "select * " it is retrieving always a some order (but this order is same for all times) and where the rows are jumbled.i.e showing in an order they were entered.

I want that last but one row showing in "select * from mytable" result set..

Thanks for great help..!!|||ok, ok, i feel bad now. ;)

this will give you the second to last row, where "last" is determined by ordering the "item" column alphabetically.

declare @.t table (item varchar(10))

insert into @.t
select 'aaa' union all
select 'bbb' union all
select 'ccc' union all
select 'ddd' union all
select 'eee' union all
select 'fff'

select top 1 a.* from
(select top 2 * from @.t order by item desc) a
order by item asc

Your query is working fine...i am getting what i want..But i can create a table variable for a existing table..and how can run your query on a existing table without insertion of new data?

Thanks|||it's just an example. do you understand what the example is doing?

just alter the query to target your table instead of @.t, and alter "item" to whatever column you want to order by.|||-It is retrieving only row 1 based on the primary key of the table.I am not willing to use primary key.

Thanks

that was meant to be a little joke. you probably don't know much sql if you thought that might give you what you wanted. :)

you might want to spend some time learning SQL better.|||when i "select * " it is retrieving always a some order (but this order is same for all times) no it isn't

it only appears to be the same order every time

it might even actually be exactly the same order, many times in a row

but without an ORDER BY clause, there is no guarantee of any order in the results

How to filter the row in merge replication.

Hi There,
I would like to filter the row in several tables in merge replication
for the subscribers. I would like to filter the row with the criteria
saying only trasfer the data for last week or latest last(7 days data)
to the subcriber and the second option is first 100 rows. If there is
any information in this please forward to me.
Thanks a lot.
Indra.
Indra,
there is a parameter on the merge agent that you might like to look
at: -MaxDownloadChanges.
However, I'd like to know a little more about your scenario. On the
publisher no doubt there is some data older than a week. Is this data
intended to exist on the subscriber? What about if some of this older data
is modified on the publisher, should the change be propagated? Please post
up a bit more info.
TIA,
PAul Ibison
|||You can use static row filtering, which is documented in Books Online.
thanks
gopal
|||Hi Paul,
I reply for this message long time back but its not apper here, replying
again.
Acutally we have one server working as publisher, distributer and
several subscriber (install MSDE, sql client utility) and having adp
front end for the applicaiton. since they donot need all the data, i
just wanted to send them for few table data of say last two week or 20
etc. actuall publisher may have data which have been modified in the
main office, which in not necessary to send it back to them, becasue we
are receiving all the job information form the field office and once we
received it we will process othe information here in main office and it
not necessary to replicate or propagated back to the subscriber.
As mention by Gopal, I try to check with static filter its giving me
porblem. I willtry again tomorrow and let you know how its work.
Thanks for help.
Indra.
*** Sent via Developersdex http://www.codecomments.com ***
Don't just participate in USENET...get rewarded for it!
|||One thing to be very careful with is what you want the subscriber to have.
When you implement a filter, merge will literally enforce that filter across
your data. That means if your filter is for say the last 20 days and
someone inserts a row of data older than this, that piece of data will be
removed from the subscriber after it is sent to the publisher.
Mike
Principal Mentor
Solid Quality Learning
"More than just Training"
SQL Server MVP
http://www.solidqualitylearning.com
http://www.mssqlserver.com