我需要将来自同一个表的两个查询合并到一个表中:
SELECT
t.[Origin Terminal Name] as 'Terminal',
COUNT(t.[Pro Number]) as 'Inbound Shipments',
SUM(t.[Total Revenue]) as 'Inbound Revenue'
FROM [AX2cTestStage].[dbo].[AX2cTestAdapter_dbo_AAATRANSPORTTABLE_V] t
GROUP BY t.[Origin Terminal Name]
ORDER BY t.[Origin Terminal Name] ASC
SELECT
t.[Destination Terminal Name] as 'Terminal',
COUNT(t.[Pro Number]) as 'Outbound Shipments',
SUM(t.[Total Revenue]) as 'Outbound Revenue'
FROM [AX2cTestStage].[dbo].[AX2cTestAdapter_dbo_AAATRANSPORTTABLE_V] t
GROUP BY t.[Destination Terminal Name]
ORDER BY t.[Destination Terminal Name] ASC
它们都产生了以下结果:
Terminal Inbound Shipments Inbound Revenue
Abilene 520 75970.08
Albany 877 130560.28
Terminal Outbound Shipments Outbound Revenue
Abilene 2684 419523.83
Albany 2820 407871.89
我需要这个作为输出:
Terminal Inbound Shipments Inbound Revenue Outbound Shipments Outbound Revenue
Abilene 520 75970.08 2684 419523.83
Albany 877 130560.28 2820 407871.89
我尝试了以下查询:
SELECT
t.[Origin Terminal Name] as 'Terminal',
COUNT(t.[Pro Number]) as 'Inbound Shipments',
SUM(t.[Total Revenue]) as 'Inbound Revenue',
(SELECT
t2.[Destination Terminal Name] as 'Terminal',
COUNT(t2.[Pro Number]) as 'Outbound Shipments',
SUM(t2.[Total Revenue]) as 'Outbound Revenue'
FROM [AX2cTestStage].[dbo].[AX2cTestAdapter_dbo_AAATRANSPORTTABLE_V] t2
GROUP BY t2.[Destination Terminal Name])
FROM [AX2cTestStage].[dbo].[AX2cTestAdapter_dbo_AAATRANSPORTTABLE_V] t
LEFT JOIN [AX2cTestStage].[dbo].[AX2cTestAdapter_dbo_AAATRANSPORTTABLE_V] t2 ON t.[Origin Terminal Name] = t2.[Destination Terminal Name]
GROUP BY t.[Origin Terminal Name]
ORDER BY t.[Origin Terminal Name] ASC
我收到这个错误:
msg 116,level 16,state 1,line 22当子查询没有引入exists时,只能在select列表中指定一个表达式。
子查询是解决这个问题的方法吗?我很感激你的建议
2条答案
按热度按时间a1o7rhls1#
如果我跟对了,你可以用
cross apply
要取消将列拆分为行,然后进行聚合,请执行以下操作:velaa5lx2#