我有一张表格可以存储许多不同的价值观。通过列(TYPE)值可以是" A"," B"或" C"。
当我执行select来检索值时,我需要执行一些操作,比如应用子查询来检索别名值,如果TYPE等于" A"这与子查询到TYPE" B"。
不同现在我有2个查询:一个用于类型" A"另一种类型" B"。我想把这些问题放在一起,但我找不到如何做的方法。
输入" A"
SELECT distinct(l.ProcessId),
(SELECT Date from Log lt WHERE lt.ProcessId = l.ProcessId and lt.Message like '%SENDING%') as DateStart,
(SELECT Date from Log lt WHERE lt.ProcessId = l.ProcessId and lt.Message like '%DONE%') as DateEnd,
DATEDIFF(ss, (SELECT Date from Log lt WHERE lt.ProcessId = l.ProcessId and lt.Message like '%SENDING%'), (SELECT Date from Log lt WHERE lt.ProcessId = l.ProcessId and lt.Message like '%DONE%')) as Duration
FROM notifier.Log l where l.Who = 'QueryString' and l.Type = 'A'
输入" B"
SELECT distinct(l.ProcessId),
Date as DateStart,
Date as DateEnd,
DATEDIFF(ss, Date, Date) as Duration
FROM notifier.Log l where l.Type = 'B';
如何执行唯一选择以检索类型" A"和" B"?
答案 0 :(得分:2)
您是否在寻找UNION {ALL}?用于在一个结果中检索两个分开的选择。
e.g。
select column_A from table_A where Column_A='Value_A'
UNION ALL
select column_B from table_B where Column_B='Value_B'
请注意,列必须相同才能生效, union 会在不重复行的情况下加入,同时 union all 允许重复的行。< / p>
问候。
答案 1 :(得分:1)
您需要使用UNION
。
试试这个:
SELECT DISTINCT (l.ProcessId),
(
SELECT DATE
FROM Log lt
WHERE lt.ProcessId = l.ProcessId
AND lt.Message LIKE '%SENDING%'
) AS DateStart,
(
SELECT DATE
FROM Log lt
WHERE lt.ProcessId = l.ProcessId
AND lt.Message LIKE '%DONE%'
) AS DateEnd,
DATEDIFF(ss, (
SELECT DATE
FROM Log lt
WHERE lt.ProcessId = l.ProcessId
AND lt.Message LIKE '%SENDING%'), (
SELECT DATE
FROM Log lt
WHERE lt.ProcessId = l.ProcessId
AND lt.Message LIKE '%DONE%'
)) AS Duration
FROM notifier.Log l
WHERE l.Who = 'QueryString'
AND l.Type = 'A'
UNION ALL
SELECT DISTINCT (l.ProcessId),
DATE AS DateStart,
DATE AS DateEnd,
DATEDIFF(ss, DATE, DATE) AS Duration
FROM notifier.Log l
WHERE l.Type = 'B'
为了将两个或多个查询的结果集“合并”到一个结果集中,您必须使用UNION ALL
。
但请注意,两个查询必须返回相同数量的列才能使其正常工作,否则您将收到一条错误消息,指出查询返回的列数不同。
此外,您将能够通过将您的两个查询封装在另一个SELECT
语句中来进一步过滤此结果集,但这已经超出了主题。