Showing posts with label users. Show all posts
Showing posts with label users. 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?

Wednesday, March 28, 2012

Help with SQL Agent Security

Hi,
I want to be able to allow certain non (SA) users to see SQL Agent
jobs. Whilst I am aware that all I need to do is add
them to the 'TargetServersRole'(and fix any sp3 changes), this does
not allow them to see the status of any jobs. This is because when
they
look at the jobs, sp_get_composite_job_info runs a check
to see if they are sysadmin before running
xp_sqlagent_enum_jobs. If they aren't sysadmin the
status gets returned as not running (4).
You will note that all jobs have a status of 'Not Running' even though
some are definitely running ie. replication tasks
The following posting is exactly what I have an issue with and would
like to resolve.
http://groups.google.com.au/groups?...80a%2540phx.gblThere is no supported way to do this. In terms of using
TargetServerRole, that's not officially supported either.
Using the role isn't documented as it's used by SQL Server
for multi-server administration and it's permissions has
changed through some of the service packs.
Essentially, the behavior you are seeing is by design.
-Sue
On 17 Feb 2005 20:50:18 -0800, jharalam@.colesmyer.com.au
(Jharalam) wrote:

>Hi,
>I want to be able to allow certain non (SA) users to see SQL Agent
>jobs. Whilst I am aware that all I need to do is add
>them to the 'TargetServersRole'(and fix any sp3 changes), this does
>not allow them to see the status of any jobs. This is because when
>they
>look at the jobs, sp_get_composite_job_info runs a check
>to see if they are sysadmin before running
>xp_sqlagent_enum_jobs. If they aren't sysadmin the
>status gets returned as not running (4).
>You will note that all jobs have a status of 'Not Running' even though
>some are definitely running ie. replication tasks
>The following posting is exactly what I have an issue with and would
>like to resolve.
>http://groups.google.com.au/groups?...80a%2540phx.gbl|||If using windows NT Authenication, make sure that you log into SQL
Server exectaly how your UseriD is defined in Windows in the CORRECT
case
e.g in Windows your user is
DOMAIN\Your.Name
sign on as DOMAIN\Your.Name not DOMAIN\your.name there is an Extended
Stored Procedure that does some sort of binary User Name comparison
to check your credentials and this can sometimes prevent you from
seeing the Job Status as it evaluates: Your.Name <> your.name
as false.
This is of course a BUG! Opps Feature of the system
Paul

Friday, March 23, 2012

Help with Select statement

I need help creating a select statement that will show users who have
attempted to fill out a form more than once and have not completed it
at least once.
Here is the basic table layout.
ID int PK
PersonID int
Completed bit
Date DateTime
The data looks like this
ID Person ID Completed Date
1 101 True 5/1/06
2 102 True 5/2/06
3 103 False 5/3/06
4 104 True 5/3/06
5 103 True 5/3/06
6 105 False 5/3/06
7 105 True 5/4/06
8 105 False 5/4/06
9 106 True 5/4/06
10 104 True 5/4/06
I need to select all users who have attempted to fill out the form
multiple times and have failed to complete the form(a False in the
Completed column) at least one of those times. So for the above data
I would want the results of the select to be
ID Person ID Completed Date
3 103 False 5/3/06
5 103 True 5/3/06
6 105 False 5/3/06
7 105 True 5/4/06
8 105 False 5/4/06
Can anyone help me with this.
Thanksselect ID,
PersonID,
Completed,
Date
from mytable
where PersonID in (
select PersonID
from mytable
group by PersonID
having count(*)>1
and min(cast(Completed as int))=0)|||It worked great. Thank You.

Help with Security!

I have a web application for which I am required to authenticate users at the database level (no generic or application type logins permitted). I am not permitted to use Active Directory because we do not have AD installed. We chose to use standard SQL accounts. I have two groups of users:

1. Normal users
2. Super Users (can do everything a normal user can do, plus can add/delete/modify user accounts)

When a Super User is created, they are added to three fixed roles Security Administrator (Server Role) and db_accessadmin and db_securityadmin (Database Roles).

A normal user is assigned to some custom roles that we created, but is not assigned to any fixed roles (database or server) other than the default Public role.

The problem comes when a Super User attempt to add another Super user. The process fails because the Super user does not have sufficient privileges to run sp_addrolemember. The following two statements fail because of permissions:

sp_addrolemember 'db_securityadmin', N'mySuperUser'
sp_addrolemember 'db_accessadmin', N'mySuperUser'

Additional research indicates that I am required to be a member of the SysAdmin fixed role of the db_Owner role in order to have access to sp_addrolemember.

Does anyone have any suggestions for a workaround? This is pretty frustrating. I am unwilling to let my Super Users have sysadmin or db_owner rights. These grant far more access than is needed. I just want my super users to be able to add and administer normal user accounts and other Super User accounts.

Thanks,

Hugh ScottI think you are using SQL2K, if so how about using Application roles? I have not done this before but it might be worth checking out. Look up Application Roles in BOL.

My theory is that you could setup an application role with dbo authority. When you need to create a superuser you would make an additional connection to the db using an application role, create the super user and then drop the connection.|||Ding!

You are correct. I should have stated that we were using SQL 2K. I like your idea and I will give it a shot.

Thanks!

Hugh

Originally posted by Paul Young
I think you are using SQL2K, if so how about using Application roles? I have not done this before but it might be worth checking out. Look up Application Roles in BOL.

My theory is that you could setup an application role with dbo authority. When you need to create a superuser you would make an additional connection to the db using an application role, create the super user and then drop the connection.sql

Wednesday, March 21, 2012

Help with roles in SQL Server Reporting Services 2005

I know how to create roles but how do you add users to them, and then roles to different levels? This section of MSDN doesn't tell much

http://msdn2.microsoft.com/en-us/library/ms157397(en-US,SQL.90).aspx

You add users to the roles by navigating to the item you wish to secure. You then click on the property tab, then the security sub-tab. From here you can click on 'New Role Assignment'. Now you can add a user or group and assign the role you wish for them to have on this item.

You can also do this at the site level for the site level permissions. Click on 'Site Settings' in the upper right hand corner. Then click on 'Configure site-wide security'. From here you can again add users and assign them different system roles.

-Daniel

Monday, March 12, 2012

Help with query

I have 3 tables

A table of users containing the fields always required for a user.
users:
userid
email
name
password
projectid

A table of extra properties for a user that can be different from each
project.
These properties can be "location", "department", and so on.
userproperties
userpropertyid
propertyname
projectid

A table of the value of each of the extra properties for each user
userpropertyvalues
userpropertyid
userid
userpropertyvalue

Now I want to do a select statement that returns

userid, email, name, password, propertyname[1], propertyname[2],
propertyname[3]

[userid],[email],[name],[password],[propertyvalue1],[propertyvalue2],propertyvalue[3]

(when I pass a projectid)

I just don't seem to be able to do that. Any ideas?

Thank you very much in advance.

FlemmingHi

You design does not look to be correct. If a user can only be in one project
then I would not expect projectid to be in userproperties but I would expect
userid to appear in it. If a user can have multiple projects then I would
expect both to be in userproperties and userpropertyvalues. It is also not
clear how you would rank these assuming propertyid is a numeric then the
first property has the the minimum propertyid, the second property is the
minimum propertyid greater then the first propertyid, the third property is
the minimum propertyid greater then the second propertyid. You can then join
to the users to userproperties/userpropertyvalues three times to get the
values you want.

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

<flemming.madsen@.gmail.com> wrote in message
news:1111790204.659952.289470@.z14g2000cwz.googlegr oups.com...
>I have 3 tables
> A table of users containing the fields always required for a user.
> users:
> userid
> email
> name
> password
> projectid
> A table of extra properties for a user that can be different from each
> project.
> These properties can be "location", "department", and so on.
> userproperties
> userpropertyid
> propertyname
> projectid
> A table of the value of each of the extra properties for each user
> userpropertyvalues
> userpropertyid
> userid
> userpropertyvalue
>
> Now I want to do a select statement that returns
> userid, email, name, password, propertyname[1], propertyname[2],
> propertyname[3]
> [userid],[email],[name],[password],[propertyvalue1],[propertyvalue2],propertyvalue[3]
> (when I pass a projectid)
> I just don't seem to be able to do that. Any ideas?
> Thank you very much in advance.
> Flemming|||(flemming.madsen@.gmail.com) writes:
> A table of users containing the fields always required for a user.
> users:
> userid
> email
> name
> password
> projectid
> A table of extra properties for a user that can be different from each
> project.
> These properties can be "location", "department", and so on.
> userproperties
> userpropertyid
> propertyname
> projectid
> A table of the value of each of the extra properties for each user
> userpropertyvalues
> userpropertyid
> userid
> userpropertyvalue
>
> Now I want to do a select statement that returns
> userid, email, name, password, propertyname[1], propertyname[2],
> propertyname[3]
>
[userid],[email],[name],[password],[propertyvalue1],[propertyvalue2],propert
yvalue[3]
> (when I pass a projectid)
> I just don't seem to be able to do that. Any ideas?

For this kind of questions, it always a good idea to include:

o CREATE TABLE statements for your tables.
o INSERT statements with sample data.
o The desired result given the sample.

This permits anyone who answer to post a tested query.

In you case, there are several loose ends. For instance, in the
userpropertyvaules, I would expect a projectid, since I would
expect (projectid, userpropertyid) to be the primary key of
userproperties. It seems now that userpropertyid alone is the
key. Another loose end is how you now which propertyvalue is #1
and so on. Furthermore, do we know if all users have all properties
for a project?

So this query is very much just a sketch, but hopefully you can work
from it.

SELECT u.userid, u.email, u.name, u.password, upv1.userpropertyvalue,
upv2.userpropertyvalue, upv3.userpropertyvalue
FROM users u
JOIN userproperties up1 ON u.projectid = up1.projectid
JOIN userproperties up2 ON u.projectid = up2.projectid
JOIN userproperties up2 ON u.projectid = up2.projectid
LEFT JOIN userpropertyvalues upv1
ON up1.userpropertyid = upv1.userpropertyd
AND upv1.userid = u.userid
LEFT JOIN userpropertyvalues upv2
ON up2.userpropertyid = upv2.userpropertyd
AND upv2.userid = u.userid
LEFT JOIN userpropertyvalues upv3
ON up3.userpropertyid = upv3.userpropertyd
AND upv3.userid = u.userid
WHERE u.projectid = @.projectid
AND up1.projectid = @.projectid
AND up2.projectid = @.projectid
AND up3.projectid = @.projectid

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

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

Your query works. Thank you very much.

One issue though: I might not in advance be aware of the number of
properties for each user.

Any ideas on alterting the query (or splitting it up) so I can deal
with that?

Thank you very much,
Flemming|||Update:

Erland,

I modified your proposal slightly and I have now solved my problem.

Once again, thank you very much for your kind help.

Sincerely,
Flemming|||Erland Sommarskog (esquel@.sommarskog.se) writes:
> SELECT u.userid, u.email, u.name, u.password, upv1.userpropertyvalue,
> upv2.userpropertyvalue, upv3.userpropertyvalue
> FROM users u
> JOIN userproperties up1 ON u.projectid = up1.projectid
> JOIN userproperties up2 ON u.projectid = up2.projectid
> JOIN userproperties up2 ON u.projectid = up2.projectid
> LEFT JOIN userpropertyvalues upv1
> ON up1.userpropertyid = upv1.userpropertyd
> AND upv1.userid = u.userid
> LEFT JOIN userpropertyvalues upv2
> ON up2.userpropertyid = upv2.userpropertyd
> AND upv2.userid = u.userid
> LEFT JOIN userpropertyvalues upv3
> ON up3.userpropertyid = upv3.userpropertyd
> AND upv3.userid = u.userid
> WHERE u.projectid = @.projectid
> AND up1.projectid = @.projectid
> AND up2.projectid = @.projectid
> AND up3.projectid = @.projectid

Flemming said that my query worked, which is sort of funny, because I
forgot there conditions in the WHERE clause, which I had intended to
read:

WHERE u.projectid = @.projectid
AND up1.projectid = @.projectid
AND up2.projectid = @.projectid
AND up3.projectid = @.projectid
AND up1.propertyname = 'propertyname1'
AND up2.propertyname = 'propertyname2'
AND up3.propertyname = 'propertyname3'

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

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

Friday, March 9, 2012

help with query

Hi, need some help...
The problem I face is that the last column in the select list which is
[Amount2]
returns the sum of all users sum so each row in the returned result has the
same number.
The [Amount1] column returns the correct sum per each user due to the
grouping.
How shall I do this?
SELECT u.Col1, u.Col2, u.Col3, SUM(t.amount) AS Amount1 /* this SUM is OK
*/,
(SELECT SUM(t.amount) /* this SUM is not OK */
FROM dbo.Table1 T1
INNER JOIN dbo.Table2 T2 ON T1.TransId = T2.TransId
INNER JOIN dbo.Table3 T3 ON T3.LoanId = T2.LoanId
INNER JOIN dbo.Table4 T4 ON T4.UserId = T3.UserId
WHERE T3.UserId IN (1, 2, 3)
AND T3.TypeId = 2
) AS Amount2
FROM dbo.Table1 T1
INNER JOIN dbo.Table2 T2 ON T1.TransId = T2.TransId
INNER JOIN dbo.Table3 T3 ON T3.LoanId = T2.LoanId
INNER JOIN dbo.Table4 T4 ON T4.UserId = T3.UserId
WHERE T3.UserId IN (1, 2, 3)
AND T3.TypeId = 1
GROUP BY T4.Col1, T4.Col2, T4.Col3
Thanks,
YanivYaniv
I did some testing on Northwind database
select Customerid, count(employeeid),
(select count(employeeid) from orders
where Customerid in ('vinet','hanar')) as d
from orders
where Customerid in ('vinet','hanar')
group by Customerid
--Customerid d
-- -- --
HANAR 14 19
VINET 5 19
select Customerid, count(employeeid),
(select count(o.employeeid) from orders o
where orders.Customerid=o.Customerid) as d
from orders
where Customerid in ('vinet','hanar')
group by Customerid
--Customerid d
-- -- --
HANAR 14 14
VINET 5 5
You did not have a group by customerid in my case ,thus you've got the
wrong output
See if my example helps you otherwise please post your ddl + expected result
"Yaniv" <yanive@.rediffmail.com> wrote in message
news:ettjcwM9FHA.2264@.tk2msftngp13.phx.gbl...
> Hi, need some help...
> The problem I face is that the last column in the select list which is
> [Amount2]
> returns the sum of all users sum so each row in the returned result has
> the same number.
> The [Amount1] column returns the correct sum per each user due to the
> grouping.
> How shall I do this?
> SELECT u.Col1, u.Col2, u.Col3, SUM(t.amount) AS Amount1 /* this SUM is OK
> */,
> (SELECT SUM(t.amount) /* this SUM is not OK */
> FROM dbo.Table1 T1
> INNER JOIN dbo.Table2 T2 ON T1.TransId = T2.TransId
> INNER JOIN dbo.Table3 T3 ON T3.LoanId = T2.LoanId
> INNER JOIN dbo.Table4 T4 ON T4.UserId = T3.UserId
> WHERE T3.UserId IN (1, 2, 3)
> AND T3.TypeId = 2
> ) AS Amount2
> FROM dbo.Table1 T1
> INNER JOIN dbo.Table2 T2 ON T1.TransId = T2.TransId
> INNER JOIN dbo.Table3 T3 ON T3.LoanId = T2.LoanId
> INNER JOIN dbo.Table4 T4 ON T4.UserId = T3.UserId
> WHERE T3.UserId IN (1, 2, 3)
> AND T3.TypeId = 1
> GROUP BY T4.Col1, T4.Col2, T4.Col3
>
> Thanks,
> Yaniv
>|||Great, this is what I need.
Many many thanks.
"Uri Dimant" <urid@.iscar.co.il> wrote in message
news:%23$x6W5M9FHA.132@.TK2MSFTNGP15.phx.gbl...
> Yaniv
> I did some testing on Northwind database
> select Customerid, count(employeeid),
> (select count(employeeid) from orders
> where Customerid in ('vinet','hanar')) as d
> from orders
> where Customerid in ('vinet','hanar')
> group by Customerid
> --Customerid d
> -- -- --
> HANAR 14 19
> VINET 5 19
>
> select Customerid, count(employeeid),
> (select count(o.employeeid) from orders o
> where orders.Customerid=o.Customerid) as d
> from orders
> where Customerid in ('vinet','hanar')
> group by Customerid
> --Customerid d
> -- -- --
> HANAR 14 14
> VINET 5 5
>
> You did not have a group by customerid in my case ,thus you've got the
> wrong output
> See if my example helps you otherwise please post your ddl + expected
> result
>
>
> "Yaniv" <yanive@.rediffmail.com> wrote in message
> news:ettjcwM9FHA.2264@.tk2msftngp13.phx.gbl...
>