创建动态数据SQL

时间:2018-03-26 04:34:48

标签: sql sql-server sql-server-2005

我的sql server数据库中有两个表

第一桌

SID--Role
1--A
2--B
3--C
4--D
5--E

第二桌

RoleName--SID
Admin--1
Admin--4
QA--2

Rolename'Admin'的输出应为

SID--Role--Exists
1--A--true
2--B--false
3--C--false
4--D--true
5--E--false

你们可以帮我一个选择查询来获得上述输出

3 个答案:

答案 0 :(得分:1)

您似乎需要执行@Override public void onBackPressed() { if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); } if (doubleTap) { super.onBackPressed(); } else { Toast toast = Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); webView.getUrl(); doubleTap = true; Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { doubleTap = false; } }, 2000); } }(即joins)并使用left join表达式检查角色(即管理员)是否存在。

case

但是,如果支持

,您还可以使用select t.SID, t.Role, case when (t2.RoleName is not null and t2.RoleName = 'Admin') then 'true' else 'false' end [Exists] from table1 t left join table2 t2 on t2.sid = t.sid SQL标准ANSI函数
COALESCE()

答案 1 :(得分:0)

利用CASE并离开外部加入

SELECT A.SID, A.Role,CASE  RoleName WHEN 'Admin' THEN 'True' ELSE 'False' end AS 'Exists'
FROM  #TEMP_ROLE A LEFT OUTER JOIN #TEMP_ROLENAME ON a.SID = #TEMP_ROLENAME.SID

答案 2 :(得分:0)

您也可以尝试此查询

DECLARE  @Role TABLE ([SID] INT,[Role] VARCHAR(1))
INSERT INTO @Role
SELECT 1,'A' UNION ALL SELECT 2,'B' UNION ALL SELECT 3,'C' UNION ALL SELECT 4,'D' UNION ALL SELECT 5,'E'

DECLARE @RoleDetails TABLE (SID INT,RoleName VARCHAR(100))
INSERT INTO @RoleDetails
SELECT 1,'ADMIN' UNION ALL SELECT 4, 'ADMIN' UNION ALL SELECT 2,'QA'

(SELECT B.[SID],A.[Role],'True' AS EXIST FROM @Role A 
INNER JOIN @RoleDetails B ON A.[SID] = B.[SID] AND B.RoleName = 'ADMIN')
UNION ALL
(SELECT A.[SID],A.[Role],'False' AS EXIST FROM @Role A 
LEFT JOIN @RoleDetails B ON A.[SID] = B.[SID] WHERE A.[SID] NOT IN 
(SELECT A.[SID] FROM @Role A INNER JOIN @RoleDetails B ON A.[SID] = B.[SID] AND B.RoleName = 'ADMIN')) 

谢谢