我需要一些帮助,在附加列中添加“注释”以及带有where子句的select语句。
当前代码
第一声明
SELECT * FROM [Table] WHERE [Dep] = 'M' AND
([Join M] <> [Join B] OR
[Resign M] <> [Resign Date Beneficiary])
GO
第二声明
SELECT * FROM [Table] WHERE [Join B] < [Resign B] AND
([Join M] > [Join B] OR
[Resign M] < [Resign B])
GO
这是两个不同的select语句,但是我想将两个输出合并到一个表中。
错误代码 - (示例解释)
第一声明
SELECT * FROM [Table] WHERE [Dep] = 'M' AND
([Join M] <> [Join B] OR
[Resign M] <> [Resign Date Beneficiary])
SET AS [Comment] = 'Main'
GO
第二声明
SELECT * FROM [Table] WHERE [Join B] < [Resign B] AND
([Join M] > [Join B] OR
[Resign M] < [Resign B])
SET AS [Comment] = 'Date'
GO
要求是在输出中添加一个额外的列并添加一个评论&#39;在现场,还要将两个输出组合在一个表中。
输出
第一个声明输出
[Number] |[Dep] |[Join M] |[Join B] |[Resign M ]|[Resign B]
10003 |M |20160101 |20160201 |20160301 |20160301
10004 |M |20160101 |20160201 |20160301 |20160401
第二次声明输出
[Number] |[Dep] |[Join M] |[Join B] |[Resign M ]|[Resign B]
10000 |M |20160201 |20160201 |20160131 |20160430
10002 |M |20160501 |20160430 |20160430 |20160430
必需的输出
[Number] |[Dep] |[Join M] |[Join B] |[Resign M ]|[Resign B]|[Comment]
10000 |M |20160201 |20160201 |20160131 |20160430 |'Date'
10002 |M |20160501 |20160430 |20160430 |20160430 |'Date'
10003 |M |20160101 |20160201 |20160301 |20160301 |'Main'
10003 |M |20160101 |20160201 |20160301 |20160401 |'Main'
答案 0 :(得分:2)
使用UNION ALL
组合多个(兼容的)结果集,您可以在SELECT
子句中添加额外的表达式
SELECT [Number],[Dep],[Join M],[Join B],[Resign M ],[Resign B],'Main' as Comment
FROM [Table] WHERE [Dep] = 'M' AND
([Join M] <> [Join B] OR
[Resign M] <> [Resign Date Beneficiary])
UNION ALL
SELECT [Number],[Dep],[Join M],[Join B],[Resign M ],[Resign B],'Date' as Comment
FROM [Table] WHERE [Join B] < [Resign B] AND
([Join M] > [Join B] OR
[Resign M] < [Resign B])
或者,如果这些行代表Table
的全部内容,并且您只想将行归类为Main
或Date
,则可以使用CASE
表达式:
SELECT [Number],[Dep],[Join M],[Join B],[Resign M ],[Resign B],
CASE WHEN [Dep] = 'M' AND
([Join M] <> [Join B] OR
[Resign M] <> [Resign Date Beneficiary])
THEN 'Main'
ELSE 'Date' END as Comment
FROM [Table]
答案 1 :(得分:1)
似乎你只想在查询之间建立联合
SELECT
[Number]
, [Dep]
, [Join M]
, [Join B]
, [Resign M ]
, [Resign B]
, 'Main' AS comment
FROM [Table]
WHERE [Dep] = 'M'
AND ([Join M] <> [Join B]
OR [Resign M] <> [Resign Date Beneficiary]
)
UNION ALL
SELECT
[Number]
, [Dep]
, [Join M]
, [Join B]
, [Resign M ]
, [Resign B]
, 'Date' AS comment
FROM [Table]
WHERE [Join B] < [Resign B]
AND ([Join M] > [Join B]
OR [Resign M] < [Resign B]
)
;