sql查询根据where条件选择不同的选择列表

时间:2016-07-27 14:28:56

标签: sql .net

我需要使用需要出现授权数据的查询来选择一些数据,其余数据应标记为XXXXXXXX,但我需要在单个查询中从表中获取所有数据。

select empid, orgid, fname, lastname, mname, depid, date 
from   employee 
where  orgid in (100,200,300,400,500)

输出应该是这样的:

10  100 3 "dfdf"  "dfsdfd" "sdfsdfd" "sdfsdfd" "10/10/2010"
20  200 4 "dfdf"  "dfsdfd" "sdfsdfd" "sdfsdfd" "10/10/2010"
30  300 5 "dfdf"  "dfsdfd" "sdfsdfd" "sdfsdfd" "10/10/2010"
40  400 6 "dfdf"  "dfsdfd" "sdfsdfd" "sdfsdfd" "10/10/2010"
50  500 7 "dfdf"  "dfsdfd" "sdfsdfd" "sdfsdfd" "10/10/2010"
XX  XXXX X "xxxx"  "XXXXXX" "XXXXXXX"  "XXXXXX" "XXXXXXXXXX"
XX  XXXX X "xxxx"  "XXXXXX" "XXXXXXX"  "XXXXXX" "XXXXXXXXXX"
XX  XXXX X "xxxx"  "XXXXXX" "XXXXXXX"  "XXXXXX" "XXXXXXXXXX"
XX  XXXX X "xxxx"  "XXXXXX" "XXXXXXX"  "XXXXXX" "XXXXXXXXXX"
XX  XXXX X "xxxx"  "XXXXXX" "XXXXXXX"  "XXXXXX" "XXXXXXXXXX"
XX  XXXX X "xxxx"  "XXXXXX" "XXXXXXX"  "XXXXXX" "XXXXXXXXXX"

1 个答案:

答案 0 :(得分:0)

select empid, orgid, fname, lastname, mname, depid, date
from   employee 
where  orgid in (100,200,300,400,500)
UNION ALL
select 0, 0, 'XXXX', 'XXXX', 'XXXX', 0, '1900-01-01'
from   employee 
where  orgid NOT in (100,200,300,400,500)

以上查询应该完成这项工作。但是,如果您特别关注“xx ...”'在结果集中,您需要将结果集转换为varchar(nn)。

下面是一个示例(当然,您需要替换字段和表名)

SELECT CAST(CourseId AS VARCHAR(20)), Title, CAST(Credits AS VARCHAR(20)),
CAST(DepartmentID AS VARCHAR(20)), CONVERT(VARCHAR(20), GetDate(),101) 
FROM Course
WHERE DepartmentID IN (1, 2)
UNION ALL
SELECT 'xx', 'XXXX', 'xxx', 'xxxx', 'XXXXXX' FROM Course
WHERE DepartmentID NOT IN (1, 2)