I have three tables :
1) UserTable
UserId UserName
1 Mike
2 John
3 Jennifer
2) FormName
fID fName
1 edit
2 cafe
3 backoffice
3)User to form
fId UserId Allowed(bit)
1 1 0
2 1 1
3 1 1
2 2 1
3 2 0
The first table is the user table with user informations.
The second table is the form table where it stores form names of application
The third table is user level table where it says which user is allowed to open which form .
I want to create sql query where I can see all information in a single table like :
UserId USerName Edit Cafe BackOffice
1 mike 0 1 1
2 john 1 1 0
I think it is possbile with SQL Fiddle and Pivot but I am having hard time to figure the right code out .
You can use the PIVOT function, but you have to cast the allowed column to something other than a bit datatype. For example, the below casts it to an int:
select userid, username,
coalesce(Edit, 0) Edit,
coalesce(Cafe, 0) Cafe,
coalesce(BackOffice, 0) BackOffice
from
(
select u.userid,
u.username,
f.fname,
cast(allowed as int) allowed
from usertable u
inner join user_form uf
on u.userid = uf.userid
inner join formname f
on uf.fid = f.fid
) d
pivot
(
max(allowed)
for fname in (Edit, Cafe, BackOffice)
) piv;
See SQL Fiddle with Demo
Related
Complete SQL Server noob here. I'm not sure how to go about finding an answer to as I'm mostly not sure what to begin searching.
I have BLOG table in my SQL Server database that stores blog posts like so
ID Title DatePosted
-----------------------------------------------
1 Why Batman is Greater than Sup... 07/15/2017
2 10 Reasons Superman is the wor... 08/02/2017
3 Sick of Metropolis? Move to Go... 08/03/2017
I have another relational table that stores blogs that users have Liked, i.e.,
UserID PostID DateLiked
-------------------------------
232413 2 08/03/2017
232413 1 07/30/2017
234285 2 08/03/2017
Now what I'd like to do is call a simple SELECT * on my BLOG table, but pass in a UserID as an argument to that query to determine if the Blog was liked by said user, so my Result set would look something like so.
Given User ID: 232413
ID Title DatePosted IsLiked
--------------------------------------------------------
1 Why Batman is Greater than Sup... 07/15/2017 1
2 10 Reasons Superman is the wor... 08/02/2017 1
3 Sick of Metropolis? Move to Go... 08/03/2017 0
Is this possible in SQL Server/Database? Any tips or helpful reading is VERY much appreciated!
Assuming DateLiked column is nullable.
I am casting result of case to bit because I think you want it as Boolean value.
Passing userId parameter as #paramUserId
DECLARE #paramUserId AS INT;
SELECT b.Id,
b.Title,
b.DatePosted,
CAST(CASE WHEN sb.DateLiked IS NULL THEN 0 ELSE 1) AS BIT) AS IsLiked
FROM BLOG AS b
INNER JOIN storesBlogs AS sb ON b.ID = sb.PostID
WHERE sb.UserID = #paramUserId
It's the result on sqlite3.
select a.ID, a.Title, a.DatePosted, case UserId when 232413 then 1 else 0 end IsLiked from BLOG a inner join LikeTable b on a.id = b.post_id;
2|10 Reasons Superman is the wor...|08/02/2017|1
1|Why Batman is Greater than Sup...|07/15/2017|1
2|10 Reasons Superman is the wor...|08/02/2017|0
select a.ID, a.Title, a.DatePosted, case UserId when 232413 then 1 else 0 end IsLiked from BLOG a left join LikeTable b on a.id = b.post_id;
1|Why Batman is Greater than Sup...|07/15/2017|1
2|10 Reasons Superman is the wor...|08/02/2017|1
2|10 Reasons Superman is the wor...|08/02/2017|0
3|Sick of Metropolis? Move to Go...|08/03/2017|0
No result satisfies the PO's requirement, but statement#2 worth considering.
select id,title,dateposted,0 as IsLiked from blog where id not in (select postid from user_liked where userid =232413)
union
select id,title,dateposted,1 as IsLiked from blog where id in (select postid from user_liked where userid =232413)
order by IsLiked desc
Result -
id title dateposted IsLiked
1 Why Batman is Greater than Sup... 2017-07-15 1
2 10 Reasons Superman is the wor... 2017-08-02 1
3 Sick of Metropolis? Move to Go... 2017-08-03 0
I have a feeds table with a json array column (UserLike) of people who like it. Table will be like:
FeedID FeedName UserLike
1 Feed 1 [{"UserID":1,"UserName":"User 1"},{"UserID":2,"UserName":"User 2"},...]
2 Feed 2 [{"UserID":1,"UserName":"User 1"},{"UserID":2,"UserName":"User 2"},...]
3 Feed 3 [{"UserID":1,"UserName":"User 1"}]
I want to get list of feeds and exactly like info of user login by compare UserID (if he has liked, or not return UserLike null, i want to get feed row even if login user is not in UserLike list).
How can I do it? Does T-SQL support some thing like:
select
FeedID, FeedName,
Json_value(UserLike, '$[UserID=1].UserName')...
The result that i'm expecting is:
FeedID FeedName UserID UserName
1 Feed 1 2 User 2
2 Feed 2 2 User 2
3 Feed 3 NULL NULL
with WHERE clause: UserID=2
--Here we take all feeds
;WITH cte AS (
SELECT DISTINCT FeedID,
FeedName
FROM dbo.feeds
--Here we take parsed JSON
), feeds AS (
SELECT FeedID,
FeedName,
UserID,
UserName
FROM [dbo].[feeds] f
CROSS APPLY OPENJSON ([UserLike])
WITH (
UserID int,
UserName nvarchar(255)
))
--And here we join them
SELECT c.FeedID,
c.FeedName,
f.UserID,
f.UserName
FROM cte c
LEFT JOIN feeds f
ON f.FeedID = c.FeedID and f.UserID = 2
Output:
FeedID FeedName UserID UserName
1 Feed 1 2 User 2
2 Feed 2 2 User 2
3 Feed 3 NULL NULL
I have 2 tables like that:
PermissionsTbl
__________________
PermissionID int NotNull
PermissionDescription nvarchar(100) NotNull
PermissionID PermissionDescription
1 Human Resources
2 Employees Data
3 Departements
ActivePermissionsTbl
________________________
ActivePermID bigint NotNull
PermissionID int NotNull
UserID int NotNull
PageActive bit NotNull
ActivePermID PermissionID UserID PageActive
1 1 1 True
2 2 1 True
3 3 2 True
what I want is show data like that:
PermissionID PermissionDescription PageActive UserID
1 Human Resources True 1
2 Employees Data True 1
3 Departements 1
1 Human Resources 2
2 Employees Data 2
3 Departements True 2
I try several methods of Join , but I failed< any suggestion please.
Thanks.
I'm sure someone can find a more elegant/efficient solution, but this appears to give you what you need:
SELECT
a.PermissionID ,
A.PermissionDescription ,
ISNULL(ap.PageActive , 0) 'PageActive' ,
a.UserID
FROM
(
SELECT DISTINCT
*
FROM permissionstbl p
CROSS JOIN
(
SELECT
userid
FROM activepermissionstbl
)
a
)
a
LEFT JOIN activepermissionstbl ap ON ap.userid = a.userid AND ap.permissionid = a.permissionid
ORDER BY a.userid
So the inner query gets the Cartesian product of the two tables and then distincts them. Then for each one of those results it gets the appropriate permission in the active permissions table.
Using a left join for this so that any null results means they don't currently have an activepermission and thus the pageactive value is false.
View Demo Here
I have a few tables:
"DCDetails" table which contains the Master data for a few diagnostics centers.
"CompanyDetails" table which contains the Master data for Companies
"Investigation" table which contains the Investigations(meaning set of medical tests to be conducted)
These are my master tables.
I also have a few mapping tables:
1. "CompanyDCMap" table which contains the MAPPING of Company to Diagnostic centers
2. "InvestigationDCMap" table which contains the MAPPING of Investigation to Diagnostic centers(Or DC for short)
I have to filter a set of DC based on two criteria which are:
the DC belongs in the "CompanyDCMap" and
Out of the DC filtered in (1), it also belongs in the "InvestigationDCMap" table.
How do I write the query for this so that I get the DC which are in both CompanyDCMap and InvestigationDCMap given I have the primary keys of "CompanyDetails" and "Investigation" tables.
I have almost given up, I am unable to think of a query which filters two sets at the same time.
Kindly help me.
UPDATE
Schema:
CompanyDetails table:
CompanyID(PRIMARY KEY), CompanyName(NVARCHAR(100))
1 Company1
2 Company2
3 Company3
Investigation Table:
InvestigationID(Primary key) , InvestigationName(NVARCHAR(100))
1 HIV+ Blood Test
2 TMT
3 Urine Test
DCDetails Table:
DCID(PRIMARY KEY), DCName(NVARCHAR(100))
1 DC1
2 DC2
3 DC3
CompanyDCMap table
CompanyDCMapID(Primary key), CompanyID(Foreign key), DCId(Foreign Key)
1 1 1
2 1 2
3 2 2
4 2 3
5 3 1
6 3 3
InvestigationDCMap table
InvestigationDCMapID(Primary Key), InvestigationID(Foreign Key), DCId(Foreign Key)
1 1 1
2 1 3
3 2 2
4 2 3
Expected Output of a query given CompanyID = 1 and InvestigationID = 2, SELECT DCId and DCName =
DCId(Int) DCName(NVARCHAR(100))
2 DC2
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID;
To get "distinct" values, you can use:
SELECT DISTINCT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID;
Or...
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
INNER JOIN dbo.CompanyDCMap AS c
ON d.DCID = c.DCId
INNER JOIN dbo.InvestigationDCMap AS i
ON i.DCId = d.DCID
GROUP BY d.DCID, d.DCName;
Better yet, since no relationships with the other tables are needed:
SELECT d.DCID, d.DCName
FROM dbo.DCDetails AS d
WHERE EXISTS (SELECT 1 FROM dbo.CompanyDCMap WHERE DCId = d.DCID)
AND EXISTS (SELECT 1 FROM dbo.InvestigationDCMap WHERE DCId = d.DCID);
This will be a much more efficient query, but if you need other columns from the other tables, you'll need to revert to the join version.
Does anyone know how can I add an integer from another table to the current selected table in SQL Server?
For example:
I have 2 tables with the following information in each table
tableA:
id username point status country
1 alvin 1 1 U.S.A
2 alvin 1 1 U.S.A
3 amy 1 0 Australia
tableB:
id username point
1 amy 1
2 alvin 1
3 ken 1
How can I sum up the total points in tableA with also add in the sum points from tableB?
I tried the following code, but seem is not working and error display:
SELECT username, (COUNT(distinct a.point) + (SELECT SUM(a.point)
FROM tableB b WHERE b.username = a.username) AS 'Points', status, country
FROM tableA
GROUP BY aco.username
And the output I expected will be:
username Points status country
alvin 3 1 U.S.A
amy 2 0 Australia
WITH Results(username,point)
AS
(
SELECT username, point FROM TableA
UNION ALL
SELECT username, point FROM TableB
)
SELECT username, sum(point) AS Points FROM Results GROUP BY username
GO
EDIT
The question has changed, so now the solution should look like this
WITH Results(username,point,status, country)
AS
(
SELECT username, point, status, country FROM TableA
UNION ALL
SELECT username, point, null, null FROM TableB
)
SELECT username, sum(point) AS Points, max(status), max(country) FROM Results GROUP BY username
GO
What is WITH ?
What is UNION ?
You don't mention why Ken doesn't appear in the output table, I assume that TableA is the 'master' list. If so I would do the following INNER JOIN which is the most simple solution.
SELECT a.username AS Username, SUM(ISNULL(a.point,0)+ISNULL(b.point,0)) as Points,
MAX(a.Status) as Status, MAX(a.Country) as Country
FROM TableA a
INNER JOIN TableB b
ON a.username=b.username
GROUP BY a.username