Optimize query of sql server - sql-server

I want number of users present in a department.i have 9 department.
now i am using "while" loop to count no of users present in an department.
Can you please suggest how to count no of users present in an department.
Department table(Columns: Id and DeptName)
User Table(Columns: Id, Name, deptId)
Please help me
Thanks
[EDIT]
User table
----------
id name deptid
1 a 1
2 b 1
3 c 2
4 d null
5 e 3
6 f 4
7 g 2
8 h 4
9 i 5
10 j 5
11 k null
Department
----------
id name
1 x
2 x1
3 y
4 y1
5 z
6 z1
Result
------
count depetname
9 all
2 x
2 x1
1 y
2 y1
2 z
0 z1
[/EDIT]

see DEMO
EDIT
you should be use RIGHT JOIN
select 'all', count(0) from users
union
SELECT department.name, COUNT(users.id) FROM users Right Outer JOIN department
ON users.deptId=department.id GROUP BY department.id

Related

SQL Server Rank Function without taking into account some flagged values

Here is my problem: I have a list of flagged values, I want to see where those values would be in the case they weren't flagged. But I don't want the other flagged values to influence the order.
Note: Flagged values are the ones with CurrentPlace 10000
ID Value CurrentPlace
------------------------
1 2 1
2 8 3
3 3 2
4 4 10000
5 5 10000
6 10 10000
Using:
select *
from
(select
id, value,
rank() over (order by Value asc) as Rank
from
tbl1) r
where
r.ID in (select id from tbl1 where CurrentPlace = 10000)
Desired output:
ID Value Rank
------------------
4 4 3
5 5 3
6 10 4
But I'm getting this instead:
ID Value Rank
------------------
4 4 3
5 5 4
6 10 6
Any help will be appreciated
Thank you guys
I've solved with
SELECT ID, Value, Rank
FROM tbl1 a
CROSS APPLY
(SELECT isnull(max(currentPlace),0) + 1 AS Rank FROM tbl1 WHERE value < a.value and currentPlace <> 10000) b
WHERE a.CurrentPlace = 10000
Please feel free to comment this out.

Check if value exist for multiple records and get one record

I have two tables.Department as follows
ID DName
1 IT
2 HR
3 Admin
Employee as follows
id fname departmentid
1 Mary 2
2 Rahul 2
3 Amit 3
4 Vivek 1
5 Preetam 1
6 Mangesh 1
7 Mary 1
Observe that there are two records for Mary (id 1 and 7) in employee table. Now I want to get result with name of employee and whether it works in HR department or not. Expected output is as follows.
fname WorksInHR
Mary Y
Rahul Y
Amit N
Vivek N
Preetam N
Mangesh n
How can i achieve this in SQL2012?
Here is one way of doing this:
select e.fname,
(case when sum(case when d.dname = 'HR' then 1 else 0 end) > 0
then 'Y' else 'N'
end) as WorksInHR
from employee e join
department d
on e.departmentid = d.id
group by e.fname;

Calculating precentage of a column with bool using two tables

Could somebody please help me create a view in SQL server to get a percentage in a new column. For example I have two tables as below.
Table 1---> Subject | Table 2---->Exam
|
SubjectID SubName | ExamID SubjectID Result (bool)
1 Science | 1 1 1
2 Maths | 2 1 1
3 English | 3 1 0
4 History | 4 2 0
5 Art | 5 2 1
6 Geography | 6 3 0
| 7 4 1
|
As you can see, many subjects do not have exams hence result will be null in a joined view. I want to show the pass percentage of a subject. For example, in result column, 1 = pass, 0 = Fail. I want the result to look like below showing null fields as well.
SubjectID SubName PassPercentage
1 Science 66.66
2 Maths 50
3 English 0
4 History 100
5 Art null
6 Geography null
Here:
SELECT
Subject.SubjectId,
Subject.SubName,
(AVG(CONVERT(decimal,Exam.Result))*100) AS PassPercentage
FROM Subject
LEFT JOIN Exam on Subject.SubjectId = Exam.SubjectId
GROUP BY Subject.SubjectId, Subject.SubName
You can round percentage result (2 or without decimals) and add % sign if you want.
Use this query:
Select *,
(Select Avg(Cast(Result as decimal)) From Exam Where SubjectID=S.SubjectID)*100 as PassPercentage
From Subject as S
Result is:
SubjectID SubName PassPercentage
----------- --------------- ---------------------------------------
1 Science 66.666600
2 Maths 50.000000
3 English 0.000000
4 History 100.000000
5 Art NULL
6 Geography NULL
(6 row(s) affected)
Subquery will be executed for each row of subject table.
do:
select s.SubjectID, s.SubName,
case COUNT(e.Result)
when 0 then null
else SUM(CAST(e.Result AS INT)) * 100 / (COUNT(s.SubjectID))
end PassPrec
from Subject s
left join Exam e on s.SubjectID = e.SubjectID
group by s.SubjectID, s.SubName
there case is to get the null. nulls don't get counted in "count" function.
you can use code like this
;with cte1 as (
select subjectid, sum(result) ResultCount
from exam group by subjectid
), cte2 as (
select e.subjectid, c.ResultCount, count(e.examid) TotalExams from cte1 c
left join exam e on e.subjectid = c.subjectid
group by e.subjectid, c.ResultCount
) select s.subname, convert(decimal(10,2), (c.ResultCount/convert(decimal(10,2),c.TotalExams)) *100) as Percentage from subject s left join cte2 c
on s.subjectid = c.subjectid

SQL Stored Procedures : Count, Join and group by but it is shown 'NULL'

I got stuck something about stored procedures I write a stored that i need to shot three columns of products count like this
SELECT
Count([TPDTN].[ProductName]) as 'Product Count',
[TPDTN].[CategoryID]
FROM
[TPDTN]
LEFT JOIN
[TPDCN] ON [TPDTN].[CategoryID] = [TPDCN].[libDocumentID]
GROUP BY
[TPDTN].[CategoryID], [TPDCN].[libDocumentID]
It shows results like this:
Product Count CategoryID
---------------------------
2 1
9 2
2 3
2 4
1 5
But I don't know how make it show
Product Count CategoryID libDocumentID
-----------------------------------------------
2 1 123456789
9 2 123456789
2 3 123456789
2 4 123456789
1 5 123456789
Producer ID (LibdocumentID) is from other table but when I SELECT [TPDCN].[libDocumentID] the value is NULL
Product Count CategoryID libDocumentID
------------------------------------------------
2 1 NULL
9 2 NULL
2 3 NULL
2 4 NULL
1 5 NULL
How can I solve it? Thank you
Just add it to the select, and if you don't need the NULL you need an INNER JOIN:
SELECT Count([TPDTN].[ProductName]) as 'Product Count',[TPDTN].[CategoryID], [TPDCN].[libDocumentID]
FROM [TPDTN]
inner join [TPDCN]
ON [TPDTN].[CategoryID] = [TPDCN].[libDocumentID]
GROUP BY [TPDTN].[CategoryID],[TPDCN].[libDocumentID]

SUM of paired columns in SQL

Iam having TableInput
A B AB ID H I
1 1 1-1 3 1 2.2 //CASE1
1 1 1-1 3 2 3.4 //CASE1
1 4 1-4 3 1 2.2
1 4 1-4 3 4 4.2
1 4 1-4 3 4 3.2
1 5 1-5 3 4 1.2
1 5 1-5 3 4 3.2
1 6 1-6 3 4 5.2
Here consider CASE1 where AB column is having value of 1-1,finding the same pair 1-1 in other rows and must add columns values in H .
There fore my result table must be like..
A B AB SUM(H) SUM(I)
1 1 1-1 3 5.6
1 4 1-4 9 9.6
1 5 1-5 8 2.4
1 6 1-6 4 5.2
Not getting idea of how to query for my output table..
Can any one please help
This is called a GROUP BY:
SELECT A, B, AB,
SUM(H) AS SumH,
SUM(I) AS SumI
FROM dbo.TableName
GROUP BY A, B, AB
You have to apply aggregate functions on columns that you want to select that are not part of the GROUP BY.
Select A,B,AB,
SUM(H) as [SUM(H)],
SUM(I) as [SUM(I)]
FROM Table1
GROUP BY A, B, AB
SELECT MAX(A), MAX(B), AB, MAX(ID), SUM(H), SUM(I)
FROM Table1
GROUP BY AB
Result:

Resources