我有两个选择查询,我试图对NULL作为列执行UNION。它仅对一个选择查询有效,但对其他查询则无效。请帮助
我正在计算B&C类型的ID的总和1234,并在ID的最终选择查询中对其进行分组,并对FTN类型的相同ID的总和执行并集操作。
这意味着B&C选择查询将始终具有“ Case”值,并且不是G。,而FTN将具有G值,并且没有Case 。
联合查询的问题是,它为B&C生成正确的结果 C,但在FTN选择查询中对G显示NULL。我该如何解决?
这是我的查询
select [ID],sum([case2018]) as [Case18] , NULL AS [G18] from
(SELECT [ID], [ID Was], SUM([Cases]) AS [Case2018], NULL AS [G2018] FROM TblX
WHERE [Package Type]='B&C' and [Year]=2018 and [ID]= 1234
GROUP BY [ID], [ID Was])
GROUP BY [ID]
union
select [ID], NULL AS [Case18] , sum([G2018]) as [G18] from
(SELECT [ID], [ID Was], SUM([G]) AS G18 ,NULL as [Case2018] FROM TblX
WHERE [Package Type]='FTN' and [Year]=2018 and [ID]= 1234
GROUP BY [ID], [ID Was])
GROUP BY [ID]
答案 0 :(得分:1)
第二个查询不起作用,因为内部查询未选择名为[G2018]
的字段。
我认为查询的嵌套不是必需的。我想您需要以下条件:
SELECT [ID], SUM([Cases]) AS [Case18], NULL AS [G18]
FROM TblX
WHERE [Package Type]='B&C' AND [Year]=2018 AND [ID]=1234
GROUP BY [ID]
UNION
SELECT [ID], NULL AS [Case18] , SUM([G]) AS [G18]
FROM TblX
WHERE [Package Type]='FTN' AND [Year]=2018 AND [ID]=1234
GROUP BY [ID]
再仔细一点看,下面的单个SELECT
不会产生预期的结果吗?
SELECT [ID], [Package Type], SUM([Cases]) AS [Case18], SUM([G]) AS [G18]
FROM TblX
WHERE [Package Type] In ('B&C', 'FTN') AND [Year]=2018 AND [ID]=1234
GROUP BY [ID], [Package Type]
答案 1 :(得分:0)
我使用的站点是http://www.dpriver.com/pp/sqlformat.htm免费的在线sql格式化工具,可立即美化SQL Server,Oracle,DB2,MySQL,Sybase和Access的sql代码。这给了我可读的SQL。
为了进行分析,我然后在excel中将B&C与FTN并排粘贴并发现了错误。然后我重新排列了FTN中的一些项目,并将拼写更改为G2018
NULL AS [Case2018],
Sum([g]) AS [G2018]
SELECT [id],
Sum([case2018]) AS [Case18],
NULL AS [G18]
FROM (SELECT [id],
[id was],
Sum([cases]) AS [Case2018],
NULL AS [G2018]
FROM tblx
WHERE [package type] = 'B&C'
AND [year] = 2018
AND [id] = 1234
GROUP BY [id],
[id was])
GROUP BY [id]
UNION
SELECT [id],
NULL AS [Case18],
Sum([g2018]) AS [G18]
FROM (SELECT [id],
[id was],
NULL AS [Case2018],
Sum([g]) AS [G2018]
FROM tblx
WHERE [package type] = 'FTN'
AND [year] = 2018
AND [id] = 1234
GROUP BY [id],
[id was])
GROUP BY [id]