Showing posts with label userid. Show all posts
Showing posts with label userid. Show all posts

Friday, March 30, 2012

Help with SQL Query

I have 2 tables:

- Users, with fields id and fullName
- Accounts, with accntID, userID, accntName, Active

I need to write a query which lists all the users, along with the
number of accounts they have.

I am using the following query -

SELECT U.id, U.fullName, Count(A.accntID) AS CountOfaccntID
FROM users AS U LEFT JOIN accounts AS A ON U.id = A.userID
WHERE A.active=Yes
GROUP BY U.id, U.fullName;

My data is as follows:

Users
=====
1, User1
2, User2

Accounts
========
1,1,User1_Accnt1,true
2,1,User1_Accnt2,true
3,2,User2_Accnt1,false

The expected output is :

1, User1, 2
2, User2, 0

But I get,

1, User1, 2

What do I need to change in the query?> What do I need to change in the query?

Only one word: instead of "WHERE" use "AND".

Razvan|||(b_naick@.yahoo.ca) writes:
> I have 2 tables:
> - Users, with fields id and fullName
> - Accounts, with accntID, userID, accntName, Active
> I need to write a query which lists all the users, along with the
> number of accounts they have.
> I am using the following query -
> SELECT U.id, U.fullName, Count(A.accntID) AS CountOfaccntID
> FROM users AS U LEFT JOIN accounts AS A ON U.id = A.userID
> WHERE A.active=Yes
> GROUP BY U.id, U.fullName;

To explain Razvan's answer a little more, this is what is happening:

Logically, in an SQL query, you start with the table in the FROM
clause, and then you build a new table every time you tack on a
new table with a JOIN operator (this can be changed with parentheses).
Eventually, the resulting table is filtered by the WHERE clause.

So you start with Users, and left-join it to Accounts. You now have
a table which has all the original rows in Users. For the matching
columns in Accounts, the columns from Accounts have the value from
that table. From the non-matching rows, you have NULL. Then comes the
WHERE clause, which says "A.Active=Yes". Which means that all rows
with NULL in A.Active are filtered away. That is, all those rows
from Users with no matching accounts are no longer in the result set.

When you change WHERE to AND, the condition A.Active=Yes moves to
the JOIN operation. This means that only the rows from Accounts
with Active=Yes are brought in, and remaining rows have NULL in
all columns. In your original query, the rows with Active=No had
values in Accounts in that intermediate table (which is only locigal).

This is indeed a common error to make, and it took me sometime as well
to understand how the FROM-JOIN co-operates with WHERE, when I started
to use this syntax.

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

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

May this solve your problem

create Table Users(UserId int primary key,Username varchar(20))

insert into Users(Userid,UserName) values(1,'User1')
insert into Users(Userid,UserName) values(2,'User2')

Create Table Accounts(AccountNo int primary key,UserId int references
Users,AccountName varchar(20),Active varchar(20))

insert into Accounts VALUES(1,1,'User1_Accnt1','true')
insert into Accounts VALUES(2,1,'User1_Accnt2','true')
insert into Accounts VALUES(3,2,'User2_Accnt1','false')

select U.*,count(case when A.Active='true' then 1 else null end) from
Users U, Accounts A
where U.userid = A.userid
group by U.Userid,U.UserName

Drop Table Accounts
Drop Table Users
Please do post DDL , DML as it become easy for others to test their
queries

With warm regards
Jatinder Singh

b_naick@.yahoo.ca wrote:
> I have 2 tables:
> - Users, with fields id and fullName
> - Accounts, with accntID, userID, accntName, Active
> I need to write a query which lists all the users, along with the
> number of accounts they have.
> I am using the following query -
> SELECT U.id, U.fullName, Count(A.accntID) AS CountOfaccntID
> FROM users AS U LEFT JOIN accounts AS A ON U.id = A.userID
> WHERE A.active=Yes
> GROUP BY U.id, U.fullName;
>
> My data is as follows:
> Users
> =====
> 1, User1
> 2, User2
> Accounts
> ========
> 1,1,User1_Accnt1,true
> 2,1,User1_Accnt2,true
> 3,2,User2_Accnt1,false
> The expected output is :
> 1, User1, 2
> 2, User2, 0
> But I get,
> 1, User1, 2
> What do I need to change in the query?

Friday, March 23, 2012

Help with SELECT statement

Hi,
I have two tables with a UserID column and need to construct a query that
lists all UserIDs from Table A that is not present in Table B.
Any help with this select statement would be appreciated
NiclasSelect A.* from TableA as A where Not Exists (select * from TableB as B
where B.UserId = A.UserId)
You can also go with a Left Outer Join but it's a little more complicated to
understand:
Select A.* from TableA as A Left Outer Join TableB as B on A.UserId =
B.UserId
Where B.UserId is Null
Sylvain Lafontaine, ing.
MVP - Technologies Virtual-PC
E-mail: http://cerbermail.com/?QugbLEWINF
"Niclas" <lindblom_niclas@.hotmail.com> wrote in message
news:eipps755FHA.4076@.tk2msftngp13.phx.gbl...
> Hi,
> I have two tables with a UserID column and need to construct a query that
> lists all UserIDs from Table A that is not present in Table B.
> Any help with this select statement would be appreciated
> Niclas
>|||A third possibility would be to use the IN clause:
Select A.* from TableA as A where A.UserId Not IN (select UserId from TableB
Where UserId is not Null)
The condition Where B.UserId is Not Null is a necessity if there is a
possibility that B.UserId can be Null; otherwise the result won't be good if
the IN clause encounter a Null value.
Sylvain Lafontaine, ing.
MVP - Technologies Virtual-PC
E-mail: http://cerbermail.com/?QugbLEWINF
"Niclas" <lindblom_niclas@.hotmail.com> wrote in message
news:eipps755FHA.4076@.tk2msftngp13.phx.gbl...
> Hi,
> I have two tables with a UserID column and need to construct a query that
> lists all UserIDs from Table A that is not present in Table B.
> Any help with this select statement would be appreciated
> Niclas
>|||Many thanks !
Niclas
"Sylvain Lafontaine" <sylvain aei ca (fill the blanks, no spam please)>
wrote in message news:emU3YG65FHA.2888@.tk2msftngp13.phx.gbl...
>A third possibility would be to use the IN clause:
> Select A.* from TableA as A where A.UserId Not IN (select UserId from
> TableB Where UserId is not Null)
> The condition Where B.UserId is Not Null is a necessity if there is a
> possibility that B.UserId can be Null; otherwise the result won't be good
> if the IN clause encounter a Null value.
> --
> Sylvain Lafontaine, ing.
> MVP - Technologies Virtual-PC
> E-mail: http://cerbermail.com/?QugbLEWINF
>
> "Niclas" <lindblom_niclas@.hotmail.com> wrote in message
> news:eipps755FHA.4076@.tk2msftngp13.phx.gbl...
>

Wednesday, March 21, 2012

Help with relations

I am using MSDE Manager for my database, and I was wondering, if data is entered on one table, IE UserID, shouldnt that same userID pop up in the related column on the foreign table as well?I don't quite see what you're getting at here

Monday, March 19, 2012

help with Query please

Hi,
I have a table with (sports) results, containing an userID, EventId and
a Time for each result recorded.
How do I select a list ordered from fastest to slowest containing the
fastest time for each userID recorded ? The challenge here, that I don't
understand how to do is to not get a list of all results for an event,
but only a single entry for each UserID with this userIDs fastest time.
Is there any way to do this except looping through each user ID from my
front end code and selecting the fastest time and build a dataset from
this that I order from a dataview ? Was hoping this could be done in SQL
rather than my VB .net code.
Any help appreciated.
Niclas
*** Sent via Developersdex http://www.examnotes.net ***It is hard to suggest something without seeing the code
SELECT * FROM Users WHERE datetime_column=
(SELECT MAX(datetime_column) FROM Users U WHERE U.userid=Users.userid)
"Niclas" <NOSpam@.Notmail.com> wrote in message
news:uEnR1rAdGHA.4900@.TK2MSFTNGP02.phx.gbl...
> Hi,
> I have a table with (sports) results, containing an userID, EventId and
> a Time for each result recorded.
> How do I select a list ordered from fastest to slowest containing the
> fastest time for each userID recorded ? The challenge here, that I don't
> understand how to do is to not get a list of all results for an event,
> but only a single entry for each UserID with this userIDs fastest time.
> Is there any way to do this except looping through each user ID from my
> front end code and selecting the fastest time and build a dataset from
> this that I order from a dataview ? Was hoping this could be done in SQL
> rather than my VB .net code.
> Any help appreciated.
> Niclas
>
> *** Sent via Developersdex http://www.examnotes.net ***|||If I understand your requirements correctly,
you can do this. Note that this will give you
all UserIDs that share the same fastest time
for an event.
SELECT s.UserID,
s.EventID,
s.RecordedTime
FROM SportsResults s
WHERE s.RecordedTime IN (SELECT MIN(s2.RecordedTime)
FROM SportsResults s2
WHERE s.EventID=s2.EventID)|||On Wed, 10 May 2006 01:23:02 -0700, Niclas wrote:

>Hi,
>I have a table with (sports) results, containing an userID, EventId and
>a Time for each result recorded.
>How do I select a list ordered from fastest to slowest containing the
>fastest time for each userID recorded ? The challenge here, that I don't
>understand how to do is to not get a list of all results for an event,
>but only a single entry for each UserID with this userIDs fastest time.
Hi Niclas,
SELECT userID, MIN([Time]) AS FastestTime
FROM YourTable
GROUP BY userID
ORDER BY FastestTime ASC
(Based on lots of assumptions - see www.aspfaq.com/5006 if I answered
the wrong question).
Hugo Kornelis, SQL Server MVP|||This is a fairly straight forward group by. See if this approach works for
you (If I understand your requirements correctly). Regardless of whether or
not this works, check out these links for a quick SQL overview. I think you
will find them helpful.
http://www.w3schools.com/sql/sql_intro.asp
http://sqlzoo.net/
Select userID
, EventId
min(Time) as BestTime
from MyTable
group by userID
, EventId
Order by BestTime
"Niclas" <NOSpam@.Notmail.com> wrote in message
news:uEnR1rAdGHA.4900@.TK2MSFTNGP02.phx.gbl...
> Hi,
> I have a table with (sports) results, containing an userID, EventId and
> a Time for each result recorded.
> How do I select a list ordered from fastest to slowest containing the
> fastest time for each userID recorded ? The challenge here, that I don't
> understand how to do is to not get a list of all results for an event,
> but only a single entry for each UserID with this userIDs fastest time.
> Is there any way to do this except looping through each user ID from my
> front end code and selecting the fastest time and build a dataset from
> this that I order from a dataview ? Was hoping this could be done in SQL
> rather than my VB .net code.
> Any help appreciated.
> Niclas
>
> *** Sent via Developersdex http://www.examnotes.net ***|||Just what I needed, works OK.
Thanks
Niclas
"Jim Underwood" <james.underwoodATfallonclinic.com> wrote in message
news:uJZvYhDdGHA.4312@.TK2MSFTNGP05.phx.gbl...
> This is a fairly straight forward group by. See if this approach works
> for
> you (If I understand your requirements correctly). Regardless of whether
> or
> not this works, check out these links for a quick SQL overview. I think
> you
> will find them helpful.
> http://www.w3schools.com/sql/sql_intro.asp
> http://sqlzoo.net/
> Select userID
> , EventId
> min(Time) as BestTime
> from MyTable
> group by userID
> , EventId
> Order by BestTime
>
> "Niclas" <NOSpam@.Notmail.com> wrote in message
> news:uEnR1rAdGHA.4900@.TK2MSFTNGP02.phx.gbl...
>

Wednesday, March 7, 2012

Help with Oracle 8i Outer Join

I have a table which stores five important facts about a user:
ID (number)
First Name
Last Name
Type
Change_Indicator

The system, for some reason, stores maiden names of the female people in this table as well except the type = ALMD.

So, if I wanted to get a persons maiden name I go:
SELECT Last_Name FROM person WHERE type = ALMD and ID = 1234

Every time a person changes his or her details (any part of the name, etc.) a new row is inserted into the table and the old rows have a change_indicator flag set to Y.

So, if I have changed my name before and I want to get my latest record, I do:
SELECT * FROM person WHERE change_indicator IS NULL and ID = 12345

As a side note, the change_indicator for a maiden name is set to (something) (or other words NOT NULL).

The query Im trying is to get all users and, if applicable, their maiden name.

Sounds like a perfect candidate for a self outer join, right?

Here is what I have:

SELECT
s.first_name,
s.last_name as married_name,
m.last_name as maiden_name
FROM
person s,
person m
WHERE
s.change_indicator is null
and s.id = m.id(+)
and m.type_code = 'ALMD'
and s.last_name != m.last_name

The last little s.last_name != m.last_name is because there can be duplicates (say if someone was once married and is now divorced their maiden name will match their last name, etc.).

Ok, theres something wrong with that query. Its not doing an outer join. Only women with maiden names are selected. Assuming the query is correct I think it has something to do with the way Oracle 8i handles the join parameters, but I cant find anything online to tell me what to look for.

Help? :)Once you start outer joining a table, all joins and conditions for that table must take into account that it may be returning NULLs for a non-match. So neither of these conditions will work as is for someone with no maiden name:

and m.type_code = 'ALMD'
and s.last_name != m.last_name

This should work:

and m.type_code (+) = 'ALMD' -- definitely
and s.last_name != m.last_name (+) -- maybe

Though I'm not sure about (+) with != (and haven't got Oracle to hand to test it). If that doesn't work you could change the last condition to:

and (m.last_name is null or s.last_name != m.last_name)|||Duh! *slaps forhead*

I totally forgot about that. When I get into work tomorrow I'll give it a try.

Thanks for the help! :)|||I'm also working on a client database in Oracle, with versioning and a "most recent" flag which is the same as your "change_indicator". And, I also had prior Transact/SQL background, where the outer join operator would not apply when checkging against a constant.

There is an interesting performance issue here. For most of the time, the queries would like to pick up the most recent version (or at least start from there ). It is tempting to have a composite index on ( ID, Change_indicator ). The question is: will Oracle include into the index a record which has a null Change_indicator ?

Upon reading the documentation again, it seems to me that an ordinary B-tree index excludes null columns only if _all_ columns are null. This is not the case, since ID will never be null. Would anyone like to comment on this ?

In my database, I've side-stepped the issue, by using Y and N for my "most_recent" flag, but never null. I feel it's safer, since I'm relying heavily on that index.|||You are correct: Oracle only excludes rows from index where ALL indexed columns are NULL. You can check this for yourself like this:

SQL> create table t (a number, b number);

Table created.

SQL> create index tx on t (a,b);

Index created.

SQL> insert into t values (1,1);

1 row created.

SQL> analyze table t compute statistics;

Table analyzed.

SQL> select index_name, num_rows from user_indexes where table_name='T';

INDEX_NAME NUM_ROWS
---------- ----
TX 1

SQL> insert into t values (2,null);

1 row created.

SQL> analyze table t compute statistics;

Table analyzed.

SQL> select index_name, num_rows from user_indexes where table_name='T';

INDEX_NAME NUM_ROWS
---------- ----
TX 2

SQL> insert into t values (null,3);

1 row created.

SQL> analyze table t compute statistics;

Table analyzed.

SQL> select index_name, num_rows from user_indexes where table_name='T';

INDEX_NAME NUM_ROWS
---------- ----
TX 3

SQL> insert into t values (null,null);

1 row created.

SQL> analyze table t compute statistics;

Table analyzed.

SQL> select index_name, num_rows from user_indexes where table_name='T';

INDEX_NAME NUM_ROWS
---------- ----
TX 3

As you can see, only the last insert of (NULL,NULL) did not get stored in the index.

BTW: andrewsc/andrewst - this could get confusing!|||>> andrewsc/andrewst - this could get confusing! <<

Thanks for pointing this out, it is an innocent coincidence.
It's not wise arguing with the moderator =:) .But then again, I'm using "andrewsc" for quite a while now, in all sorts of forums. E.g. http://www.oracle.com/forums/thread.jsp?forum=75&thread=54538&message=155898&q=#155898

For better clarity, I will add a signature.

BTW: who/why is sponsoring this forum ? Is there any commercial and/or community aspect to it ? I feel a vendor-neutral forum was long overdue in the Rdbms arena.

My best regards,

Andrew Schonberger
"andrewsc"
OTN member since Sep. 1998.|||This is a privately run forum. Paul, the admin, is an Oracle DBA. I'm a Sybase ASE DBA, and you'll find many other DBAs and such here. Luckily we're without sponsorship from vendors. ;)|||Originally posted by andrewsc
>> andrewsc/andrewst - this could get confusing! <<

Thanks for pointing this out, it is an innocent coincidence.
It's not wise arguing with the moderator =:) .But then again, I'm using "andrewsc" for quite a while now, in all sorts of forums. E.g. http://www.oracle.com/forums/thread.jsp?forum=75&thread=54538&message=155898&q=#155898

For better clarity, I will add a signature.

Hey, I just found it amusing! I wasn't suggesting you change it or anything. Mine actually stands for "Tony Andrews", but of course everybody thinks my first name is Andrew like you!