我遇到了将多个查询合并到一个输出中的麻烦。我是SQL的初学者,想知道是否有人可以提供一些关于如何完成这项工作的反馈。
这是我的代码:
SELECT [status], [queryno_i] as 'Query ID', [assigned_to_group] as 'Assigned To Group', [issued_date] as 'Issuing Date',
CASE
WHEN [status] = 3 THEN [mutation]
ELSE NULL
END AS 'Closing Date'
FROM tablename.[tech_query] WITH (NOLOCK)
SELECT
CASE
WHEN [status] = 3 THEN 'CLOSED'
ELSE 'OPEN'
END AS [State]
FROM tablename.[tech_query] WITH (NOLOCK)
SELECT
CASE
WHEN [status] = 3 THEN [mutation_int]-[issued_date_INT]
ELSE NULL
END AS [TAT]
FROM tablename.[tech_query] WITH (NOLOCK)
答案 0 :(得分:1)
如果你想把所有人都放在一起
SELECT [status],
[queryno_i] as 'Query ID',
[assigned_to_group] as 'Assigned To Group',
[issued_date] as 'Issuing Date',
CASE WHEN [status] = 3 THEN [mutation] ELSE NULL END AS 'Closing Date',
CASE WHEN [status] = 3 THEN 'CLOSED' ELSE 'OPEN' END AS [State],
CASE WHEN [status] = 3 THEN [mutation_int]-[issued_date_INT] ELSE NULL
END AS [TAT]
FROM tablename.[tech_query] WITH (NOLOCK)
答案 1 :(得分:1)
使用SQL,一切都必须是一个结果集。为了返回所有这些查询的结果,它们都必须具有相同的列(和数据类型)。
您能将所有内容组合成一个选择查询吗?
SELECT
[status]
, [queryno_i] as 'Query ID'
, [assigned_to_group] as 'Assigned To Group'
, [issued_date] as 'Issuing Date'
, CASE
WHEN [status] = 3 THEN [mutation]
ELSE NULL
END AS 'Closing Date'
, NULL AS State
, NULL AS Tat
, 1 AS QueryNumber
FROM
[tech_query]
UNION ALL
SELECT NULL,NULL,NULL,NULL,NULL,
CASE
WHEN [status] = 3 THEN 'CLOSED'
ELSE 'OPEN'
END AS [State]
, NULL
, 2 AS QueryNumber
FROM
[tech_query]
UNION ALL
SELECT NULL,NULL,NULL,NULL,NULL, NULL
CASE
WHEN [status] = 3 THEN [mutation_int]-[issued_date_INT]
ELSE NULL
END AS [TAT]
, 3 AS QueryNumber
FROM
[tech_query]
答案 2 :(得分:0)
你在找这样的东西吗?
SELECT [status], [queryno_i] as 'Query ID',
[assigned_to_group] as 'Assigned To Group', [issued_date] as 'Issuing Date',
CASE
WHEN [status] = 3 THEN [mutation]
ELSE NULL
END AS 'Closing Date',
CASE
WHEN [status] = 3 THEN 'CLOSED'
ELSE 'OPEN'
END AS [State],
CASE
WHEN [status] = 3 THEN [mutation_int]-[issued_date_INT]
ELSE NULL
END AS [TAT]
FROM tablename.[tech_query] WITH (NOLOCK)
答案 3 :(得分:0)
案例陈述是内联的
SELECT
[status],
[queryno_i] as 'Query ID',
[assigned_to_group] as 'Assigned To Group',
[issued_date] as 'Issuing Date',
CASE
WHEN [status] = 3 THEN [mutation]
ELSE NULL
END AS 'Closing Date',
CASE
WHEN [status] = 3 THEN 'CLOSED'
ELSE 'OPEN'
END AS [State],
SELECT
CASE
WHEN [status] = 3 THEN [mutation_int]-[issued_date_INT]
ELSE NULL
END AS [TAT]
FROM tablename.[tech_query] WITH (NOLOCK)
为什么nolock?
答案 4 :(得分:0)
您可以使用UNION子句
http://www.w3schools.com/sql/sql_union.asp
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
但是,通过查看3个语句,所有3个选项都来自同一个表,因此您可以组合并使用CASE语句来获得结果,而无需使用Union。