在下面的代码上使用UNION
会导致两列:
[Operator Company Name]
Sum(Gross Acres)
由于5个查询,每个[Operator Company Name]
都有5条记录(行)。
如何正确编写一个UNION
或JOIN
,其中5个查询中的每一个的结果都在一个独立的列中,然后将它们全部合并到[Operator Company Name]
上,以便新的查询输出为每列1条记录和6列(公司名称+ 5条查询结果)
SELECT [Operator Company Name],
Sum([Area (Gross Acres)]) AS [Sum(Gross Acres)]
FROM Enervus_PrivateData
WHERE [US Region] Like 'Permian'
GROUP BY [Operator Company Name];
union
SELECT [Operator Company Name],
Sum([Area (Gross Acres)]) AS [Sum(TX DEL Acres)]
FROM Enervus_PrivateData
WHERE [US Region] Like 'Permian' AND [COUNTY/PARISH] Like '*Reeves*' OR [COUNTY/PARISH] Like '*Culberson*' OR [COUNTY/PARISH] Like '*Pecos*' OR [COUNTY/PARISH] Like '*Loving*' OR [COUNTY/PARISH] Like '*Ward*' OR [COUNTY/PARISH] Like '*Winkler*'
GROUP BY [Operator Company Name];
union
SELECT [Operator Company Name],
Sum([Area (Gross Acres)]) AS [Sum(N MID Acres)]
FROM Enervus_PrivateData
WHERE [US Region] Like 'Permian' AND [COUNTY/PARISH] Like '*Dawson*' OR [COUNTY/PARISH] Like '*Borden*' OR [COUNTY/PARISH] Like '*Martin*' OR [COUNTY/PARISH] Like '*Howard*'
GROUP BY [Operator Company Name];
union
SELECT [Operator Company Name],
Sum([Area (Gross Acres)]) AS [Sum(NM DEL Acres)]
FROM Enervus_PrivateData
WHERE [US Region] Like 'Permian' AND [COUNTY/PARISH] Like '*Eddy*' OR [COUNTY/PARISH] Like '*Lea*'
GROUP BY [Operator Company Name];
union
SELECT [Operator Company Name],
Sum([Area (Gross Acres)]) AS [Sum(S MID Acres)]
FROM Enervus_PrivateData
WHERE [US Region] Like 'Permian' AND [COUNTY/PARISH] Like '*Midland*' OR [COUNTY/PARISH] Like '*Glasscock*' OR [COUNTY/PARISH] Like '*Upton*' OR [COUNTY/PARISH] Like '*Reagan*'
GROUP BY [Operator Company Name];
实际结果应在每列中包含1条记录
[Operator Company Name]
-所有查询均由[Sum(Gross Acres)]
[Sum(TX DEL Acres)]
[Sum(N MID Acres)]
[Sum(NM DEL Acres)]
[Sum(S MID Acres)]
答案 0 :(得分:1)
您应该可以使用条件聚合解决此问题。
诀窍在于在每个IIF
中使用一个SUM()
语句,该语句保存来自相应原始子查询的条件。如果满足条件,则应在SUM
中考虑该值,否则应将其忽略。
考虑:
SELECT
[Operator Company Name],
Sum([Area (Gross Acres)]) AS [Sum(Gross Acres)],
Sum(
IIF(
(
[COUNTY/PARISH] Like '*Reeves*'
OR [COUNTY/PARISH] Like '*Culberson*'
OR [COUNTY/PARISH] Like '*Pecos*'
OR [COUNTY/PARISH] Like '*Loving*'
OR [COUNTY/PARISH] Like '*Ward*'
OR [COUNTY/PARISH] Like '*Winkler*'
),
[Area (Gross Acres)],
0
)
) AS [Sum(TX DEL Acres)],
Sum(
IIF(
(
[COUNTY/PARISH] Like '*Dawson*'
OR [COUNTY/PARISH] Like '*Borden*'
OR [COUNTY/PARISH] Like '*Martin*'
OR [COUNTY/PARISH] Like '*Howard*'
),
[Area (Gross Acres)],
0
)
) AS [Sum(N MID Acres)],
Sum(
IIF(
(
[COUNTY/PARISH] Like '*Eddy*'
OR [COUNTY/PARISH] Like '*Lea*'
),
[Area (Gross Acres)],
0
)
) AS [Sum(NM DEL Acres)],
Sum(
IIF(
(
[COUNTY/PARISH] Like '*Midland*'
OR [COUNTY/PARISH] Like '*Glasscock*'
OR [COUNTY/PARISH] Like '*Upton*'
OR [COUNTY/PARISH] Like '*Reagan*'
),
[Area (Gross Acres)],
0
)
) AS [Sum(S MID Acres)]
FROM Enervus_PrivateData
WHERE [US Region] Like 'Permian'
GROUP BY [Operator Company Name];