将SELECT语句与每个语句中的聚合组合在一起

时间:2014-03-04 07:52:29

标签: sql sql-server excel join aggregate-functions

我想将2个工作的sql语句合并为一个,但我不知道如何完成这项工作。 我正在使用excel / odbc,只能读取MS SQL SERVER。

第一声明:

 SELECT CustomerLocal.LocalCustomerID, 
        Sum(Orders.OrdersEURO) AS 'Sum of OrdersEURO'
FROM MyDataBase.dbo.CustomerLocal CustomerLocal, 
     CopelandDatabase.dbo.Orders Orders
WHERE Orders.LocalCustomerID = CustomerLocal.LocalCustomerID 
      AND Orders.Plant = CustomerLocal.Plant 
      AND ((CustomerLocal.IntExtCust In ('E')))
GROUP BY CustomerLocal.LocalCustomerID
ORDER BY CustomerLocal.LocalCustomerID

,第二个陈述是:

SELECT Sales.LocalCustomerID, 
SUM (CASE WHEN Sales.DateOfInvoice BETWEEN{ts '2012-10-01 00:00:00'} AND {ts '2013-09-30 00:00:00'} 
THEN Sales.SalesEURO
ELSE 0
END) AS Sales2013 ,
SUM (CASE WHEN Sales.DateOfInvoice >= {ts '2013-10-01 00:00:00'}  
THEN Sales.SalesEURO
ELSE 0
END) AS SalesYearToDate
FROM "dbo"."Sales"
Where Sales.DateOfInvoice >= {ts '2012-10-01 00:00:00'}
Group By Sales.LocalCustomerID
ORDER BY Sales.LocalCustomerID

希望的结果(专栏):

LocalCustomerID, Sales2013, SalesYearToDate, Sum of OrdersEURO 

如何启动两者的集成组合?目前我只是在excel和vlookup中运行其余部分。

编辑:替换了第二个声明,抱歉这个错误。

2 个答案:

答案 0 :(得分:0)

尝试使用union语句

SELECT CustomerLocal.LocalCustomerID, 
    Sum(Orders.OrdersEURO) AS 'Sum of OrdersEURO'
FROM MyDataBase.dbo.CustomerLocal CustomerLocal, CopelandDatabase.dbo.Orders Orders
WHERE Orders.LocalCustomerID = CustomerLocal.LocalCustomerID AND Orders.Plant =     CustomerLocal.Plant AND ((CustomerLocal.IntExtCust In ('E')))
GROUP BY CustomerLocal.LocalCustomerID
ORDER BY CustomerLocal.LocalCustomerID
Union
SELECT CustomerLocal.LocalCustomerID, 
       Sum(Orders.OrdersEURO) AS 'Sum of OrdersEURO'
FROM MyDataBase.dbo.CustomerLocal CustomerLocal, CopelandDatabase.dbo.Orders Orders
WHERE Orders.LocalCustomerID = CustomerLocal.LocalCustomerID AND Orders.Plant =   
CustomerLocal.Plant AND ((CustomerLocal.IntExtCust In ('E')))
GROUP BY CustomerLocal.LocalCustomerID
ORDER BY CustomerLocal.LocalCustomerID

答案 1 :(得分:0)

联接应该有效:

Select a.LocalCustomerID, b.Sales2013, b.SalesYearToDate, a.[Sum of OrdersEURO]
from
(
SELECT CustomerLocal.LocalCustomerID, 
       Sum(Orders.OrdersEURO) AS 'Sum of OrdersEURO'
FROM MyDataBase.dbo.CustomerLocal CustomerLocal, CopelandDatabase.dbo.Orders Orders
WHERE Orders.LocalCustomerID = CustomerLocal.LocalCustomerID AND Orders.Plant =   
CustomerLocal.Plant AND ((CustomerLocal.IntExtCust In ('E')))
GROUP BY CustomerLocal.LocalCustomerID
) a
JOIN
(
SELECT Sales.LocalCustomerID, 
SUM (CASE WHEN Sales.DateOfInvoice BETWEEN{ts '2012-10-01 00:00:00'} AND {ts '2013-09-30 00:00:00'} 
THEN Sales.SalesEURO
ELSE 0
END) AS Sales2013 ,
SUM (CASE WHEN Sales.DateOfInvoice >= {ts '2013-10-01 00:00:00'}  
THEN Sales.SalesEURO
ELSE 0
END) AS SalesYearToDate
FROM "dbo"."Sales"
Where Sales.DateOfInvoice >= {ts '2012-10-01 00:00:00'}
Group By Sales.LocalCustomerID
) b
ON a.LocalCustomerID=b.LocalCustomerID
ORDER BY a.LocalCustomerID