我有一个具有以下结构的表“任务”
[TaskId],[CompanyId], [Year], [Month], [Value]
220,1,2018,1,50553.32
220,2,2018,2,222038.12
和另一个表,其中用户有权访问名为“ UsersCopmpanies”的表中的特定公司
[UserId], [CompanyId]
1,1
这是任务编号。公司之间转移了220。一月份的任务属于copmanyId = 1,比二月份的任务属于copmanyId = 2。
根据“ UsersCopmpanies”表,用户没有compnayid = 2的权限。
我需要做的是从“任务”表的“期望值”字段中获取两行,因为用户没有权限。 预期结果应为:
[TaskId], [CompanyId], [Year], [Month],[Value]
220,1,2018,1,50553.32
220,2,2018,2,(NULL or somenthing else for.example string 'lack of permission')
答案 0 :(得分:3)
您可以使用List<Date[]>
:
left join
答案 1 :(得分:3)
我认为使用LEFT JOIN进行此查询可以按您期望的方式工作:
CREATE TABLE #MyTasks
(TaskId int,
CompanyId int,
YearCol varchar(50),
MonthCol varchar(50),
SomeValue varchar(50)
);
GO
INSERT INTO #MyTasks
SELECT 220,1,2018,1,50553.32
UNION
SELECT 220,2,2018,2,222038.12
CREATE TABLE #MyUsersCopmpanies
(UserId int PRIMARY KEY,
CompanyId varchar(50)
);
GO
INSERT INTO #MyUsersCopmpanies
SELECT 1,1
DECLARE @MyUserParam INT = 1;
SELECT #MyTasks.TaskId, #MyTasks.CompanyId, #MyTasks.YearCol, #MyTasks.MonthCol,
CASE WHEN #MyUsersCopmpanies.UserId IS NOT NULL THEN #MyTasks.SomeValue ELSE 'lack of permission' END AS 'ValueTaskByPermissions'
FROM #MyTasks
LEFT JOIN #MyUsersCopmpanies ON #MyUsersCopmpanies.CompanyId = #MyTasks.CompanyId AND #MyUsersCopmpanies.UserId = @MyUserParam;
DROP TABLE #MyTasks
DROP TABLE #MyUsersCopmpanies
结果:
TaskId CompanyId YearCol MonthCol ValueTaskByPermissions
220 1 2018 1 50553.32
220 2 2018 2 lack of permission
答案 2 :(得分:0)
一些代码:
SELECT t.taskid,t.companyid,t.year,t.month,
(CASE WHEN u.companyid IS NOT NULL THEN t.value ELSE "lack of permission" end) AS ValueData
FROM `x_task` t LEFT JOIN x_userscopmpanies u ON u.companyid = t.companyid