我有一个查询来返回在每个位置花费了多少合同和合同,返回的内容如下:
Location | ContractStatus | Expenses
-------------+----------------+---------
New York | Ad-hoc | 2043.47
New York | Contracted | 2894.57
Philadelphia | Ad-hoc | 3922.53
Seattle | Contracted | 2522.00
问题是,对于所有临时或所有合同费用的地点,我只获得一行.我想为每个位置返回两行,如下所示:
Location | ContractStatus | Expenses
-------------+----------------+---------
New York | Ad-hoc | 2043.47
New York | Contracted | 2894.57
Philadelphia | Ad-hoc | 3922.53
Philadelphia | Contracted | 0.00
Seattle | Ad-hoc | 0.00
Seattle | Contracted | 2522.00
有什么方法可以通过SQL实现这一点吗?这是我正在使用的实际查询(SQL Server 2005):
SELECT Location,
CASE WHEN Orders.Contract_ID IS NULL
THEN 'Ad-hoc' ELSE 'Contracted' END
AS ContractStatus,
SUM(OrderTotal) AS Expenses
FROM Orders
GROUP BY Location,
CASE WHEN Orders.Contract_ID IS NULL
THEN 'Ad-hoc' ELSE 'Contracted' END
ORDER BY Location ASC, ContractStatus ASC
最佳答案 是的,构造一个表达式,仅返回adhoc的ordertotal,其他的返回0,另一个执行相反的操作,并对这些表达式求和.这将包括每个位置一行,其中两列用于adhoc,一列用于Contracted …
SELECT Location,
Sum(Case When Contract_ID Is Null Then OrderTotal Else 0 End) AdHoc,
Sum(Case When Contract_ID Is Null Then 0 Else OrderTotal End) Contracted
FROM Orders
GROUP BY Location
如果你真的想要每个单独的行,那么一种方法是:
SELECT Location, Min('AdHoc') ContractStatus,
Sum(Case When Contract_ID Is Null
Then OrderTotal Else 0 End) OrderTotal
FROM Orders
GROUP BY Location
Union
SELECT Location, Min('Contracted') ContractStatus,
Sum(Case When Contract_ID Is Null
Then 0 Else OrderTotal End) OrderTotal
FROM Orders
GROUP BY Location
Order By Location