Extract data between two tables - sql

i have two tables. one table is request types and another is request rights. based on employee rights i need to show all the request type with employee assigned request type to true. i want to get reqtype for a particular employee.
for eg:-
Request type table
------------------------
REQID REqName ISACTIVE
---------------------------------
1 a true
2 b true
3 c true
REquest Rights table
-------------------------
ID ReTYpeId EmpId ISActive
----------------------------------
1 1 21 true
2 2 21 true
3 1 22 true
RESult Table
-----------------------
REQID REqName ISACTIVE
---------------------------------
1 a true
2 b true
3 c false
How to query this one.
so far i tried this much
SELECT tt.TransactionTypeName,tt.TransactionTypeId,tt.IsActive FROM sTransactionType tt JOIN sTransactionRights tr
ON tr.TransTypeID=tt.TransactionTypeId
WHERE tt.Division=1 AND tt.IsActive=1. i tried with case in isactive .but not working at all.

Try this
SELECT REQID, REqName, ISNULL(r.ISActive, 'false') AS ISACTIVE
FROM [Request type table] t
LEFT JOIN [REquest Rights table] r ON r.ReTYpeId = t.REQID AND EmpId = 21
WHERE t.ISACTIVE = 'true'

Related

Query to fetch user names according to a condition from another table (SQL)

I have two tables:
user
id
full_name
is_admin
is_active
1
Alan
0
1
2
Carl
0
1
3
Any
0
1
4
Jane
0
1
5
Marry
0
1
6
Pedri
0
1
7
admin
1
1
8
Mota
0
0
approver
id
subordinate_id
leader_id
main_leader_id
is_active
1
1
2
3
0
2
4
5
6
1
3
1
2
4
0
(subordinate_id, leader_id and main_leader_id are foreign keys that correspond to the id column of the user table)
I would like to perform a query that brings all user names that are not admin (user table is_admin=0) and that are active (user table is_active=1), and that if they have the id in the subordinate_id column in the approver table that only brings the name of that user that has the is_active of the approver table = 0.
That is, I would like to bring users that if they have any record as subordinate_id that only bring me those that are not active in the approver table.
I tried to get the data in the following way:
SELECT
full_name
FROM user AS U
LEFT JOIN approver AS A
ON U.id = A.subordinate_id
WHERE
A.id is null
AND
U.is_admin = 0
AND
U.is_active = 1
But with this query i only get the user name that not has a register in the approver table,
and in my case i want to get the user that have a register in the approver table as subordinate_id, but not if the register have the column 'is_active' equal to 1.
In my final result I could get something like this:
Alan
carl
any
marry
Pedri
In order to make this working, you should split the conditions in the WHERE clause into:
"user" conditions: is_admin = 0 AND is_active = 1
"approver" conditions: is not a subordinate OR is_active = 0
These two groups of conditions have to be set in AND.
SELECT DISTINCT user_.id, user_.full_name
FROM user_
LEFT JOIN approver
ON user_.id = approver.subordinate_id
WHERE (user_.is_admin = 0 AND user_.is_active = 1)
AND (approver.id IS NULL OR approver.is_active = 0)
Check the demo here.
Note: the DISTINCT keyword is necessary because the JOIN operation is made between two tables having cardinality 1:n.

SQL return 1 in case switch when count is bigger than 0

I have an input list of int in a stored procedure, every id has a document, and every document has multiple subdocuments. Connected on subdocument.DocumentId = document.DocumentId.
What I have to do is return a list of objects (document.DocumentId int, IsValid bool).
The bool is true if every connected subdocument's 2 columns are not null.
PARAMLIST: list of ids
SELECT
IDS.ParamList AS documentId,
CASE
WHEN (SELECT COUNT(*)
FROM Document D
JOIN SubDocument SD ON SD.DocumentId = D.DocumentId
WHERE SD.DocumentId = IDS.ParamList
AND SD.PaymentDate IS NULL
AND SD.ConnectionContractIsAcceptedDate IS NULL) > 0
THEN 1
ELSE 0
END AS IsValid
FROM
#documentIds IDS
As you can see my logic was to make a case switch where I count every SubDocument which doesn't have at least one of the columns filled, but the query doesn't return anything just the 2 column names
Document table:
DocumentId
CreatedBy
1
John
2
Jill
SubDocument table:
SubDocumentId
DocumentId
Field1
Field2
3
1
NULL
2010-02-02
4
2
2021-01-01
2018-03-03
5
1
2020-10-10
2015-11-15
6
2
2019-10-01
2013-12-12
Here the expected result is:
DocumentId
IsValid
1
false
2
true
You can join the table variable to the tables.
Then use conditional aggregation to calculate IsValid.
declare #DocumentIds table (
DocumentId int
);
insert into #DocumentIds values (1),(2);
SELECT Doc.DocumentId, Doc.CreatedBy
, CAST(MIN(
CASE
WHEN (SubDoc.Field1 IS NULL OR SubDoc.Field2 IS NULL)
THEN 0
ELSE 1
END) AS BIT) AS IsValid
FROM Document Doc
JOIN #DocumentIds Ids
ON Ids.DocumentId = Doc.DocumentId
LEFT JOIN SubDocument SubDoc
ON SubDoc.DocumentId = Doc.DocumentId
GROUP BY Doc.DocumentId, Doc.CreatedBy
ORDER BY Doc.DocumentId;
DocumentId
CreatedBy
IsValid
1
John
False
2
Jill
True
Demo on db<>fiddle here

How to count and group not null elements in SQL Server?

I have a table where each row represents a user and each column represents a service that the customer may have hired. I need to count how many customers hired 1 service, how many hired 2 and so on. It doesn't matter what service you hire. And there is no identifier column.
In Python I was able to do this with
result = services.count(axis = 1).value_counts()
result = pd.DataFrame(result, columns = ['n_clients'])
where 'result' is the csv with the database.
The result, in this case, are like:
n_client
1
928459
2
280235
3
53731
4
16042
Edit: an example of the database to clarify:
product1
product2
product3
product4
True
True
True
True
True
True
True
True
True
True
True
In this case, the result should look like:
n_client
1
4
2
2
3
1
4
0
It looks like you want to just calculate how many products per row, then group by that number
SELECT
v.CountProducts
n_client = COUNT(*)
FROM YourTable
CROSS APPLY (VALUES (
CASE WHEN product1 = 'True' THEN 1 ELSE 0 END +
CASE WHEN product2 = 'True' THEN 1 ELSE 0 END +
CASE WHEN product3 = 'True' THEN 1 ELSE 0 END +
CASE WHEN product4 = 'True' THEN 1 ELSE 0 END
) ) v(CountProducts)
GROUP BY
CountProducts;

SQL How To? Select all items from one table, and fill in the gaps based on another table?

Firstly, thank you for your time taken out to read this and please excuse the title, I wasn't quite sure how to describe my problem.
I have two tables. One for SystemUsers and another for PrintingPermissions.
PrintingPermissions Table
ID ---- SystemUserID --- PrintGroupTypeID --- CanPrint
1 ----------- 22 ------------------------- 1 -------------------True
2 ----------- 22-------------------------- 2 -------------------True
3 ----------- 22 ------------------------- 3 -------------------False
4 ----------- 23 ------------------------- 1 -------------------True
.
.
SystemUsers Table
ID ----------- Name
22 ----------- Robert
23 ----------- John
24 ----------- Simon
25 ----------- Kate
I need a select query that will generate a list of all users and their and their PrintPermissions based on the PrintingPermissions.PrintGroupTypeID.
The thing to note is that if the User is NOT listed in the PrintPermissions table I would still like their object to be created but with a CanPrintValue of FALSE or NULL.
i.e. the output of the supplied table data above should be like the following when selecting WHERE PrintGroupTypeID = 1.
.
.
RESULT (WHERE PrintGroupTypeID = 1)
Name ----- SystemUserID ----- CanPrint
Robert --------- 22 -------------------- True
John ----------- 23 --------------------- True
Simon --------- 24 --------------------- False //-- NOT in permission table, default false created
Kate ----------- 25 --------------------- False //-- NOT in permission table, default false created
Again, thank you very much for your time and please do let me know if you don't fully understand what I'm trying to achieve.
Rob
SELECT DISTINCT su.Name, su.ID, ISNULL(pp.CanPrint, CAST 0 AS BIT) as CanPrint
FROM SystemUser su
LEFT JOIN Printing Permissions pp ON su.ID = pp.SystemUserID AND pp.PrintGroupTypeID = #TargetPrintGroupTypeID
If you want null instead of false, you can omit the ISNULL function and just select CanPrint directly. This will give you three state results (true, false, null), and will allow you to determine which users are disallowed (false) and which are not in the print group (null).
How about:
Select s.name as name,
s.id as SystemUserID,
isnull(p.canprint, 'false') as CanPrint
From systemusers s
Left outer Join printingpermissions p on s.id = p.systemuserid
Where p.printgrouptypeid = 1
Ok, I've just managed to work it out.
Here's the query:
SELECT SystemUsers.Name, ISNULL(PrintingPermissions.CanPrint, 'FALSE') AS CanPrint
FROM SystemUsers LEFT OUTER JOIN
PrintingPermissions ON SystemUsers.ID = PrintingPermissions.SystemUserID AND
PrintingPermissions.PrintingGroupTypeID = #ID

How to combine two tables to get results

The following is my master table:
tablename columnname size order
employee name 25 1
employee sex 25 2
employee contactNumber 50 3
employee salary 25 4
address street 25 5
address country 25 6
And following is my child table:
childid userid masterid isactive size order
1 1 1 Y 25 1
2 1 2 Y 25 2
3 1 3 N 0 0
4 1 4 Y 50 3
I would like to get the table name columnname from master table and size,order form child table against userid when isactive is Y in child table.
Some time, if the value is not there for the particular user than get all the values like tablename, columnname, size, order where isactive isY
I am really sorry to ask this but I am not good at SQL.
Regards.
Use INNER JOIN instead of LEFT JOIN
SELECT rcm.tablename, rcm.columnname, rcc.size, rcc.order
from report_customise_master rcm
INNER JOIN report_customise_child rcc
ON rcm.id = rcc.masterid
WHERE rcm.isactive = 'Y' and rcc.isactive = 'Y'
UPDATE 1
..., COALESCE(rcc.size, rcm.size) as Size,
COALESCE(rcc.`Order`, rcc.`order`) as `Order`