我有一个我正在处理的查询,基本上我有3列:
Code: The users Code
Orders Taken: The orders which have been taken
Orders Taken From an External Call
基本上我只需要一种方法只允许Orders From External Calls有一个where子句,当我添加我的WHERE子句时,它会为两个表做。
到目前为止我的查询:
SELECT T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
Count(T_Temp_RestrictedProductSalesHistory.CustomerCode) AS [Orders Taken],
Count(T_Temp_RestrictedProductSalesHistory.CustomerCode) AS [Orders From External Calls]
FROM T_Temp_RestrictedDiaryCalls
INNER JOIN T_Temp_RestrictedProductSalesHistory
ON (T_Temp_RestrictedDiaryCalls.CustomerCode = T_Temp_RestrictedProductSalesHistory.CustomerCode)
AND (T_Temp_RestrictedDiaryCalls.CallDate = T_Temp_RestrictedProductSalesHistory.EntryDate)
GROUP BY T_Temp_RestrictedDiaryCalls.AccreditedDomainCode;
非常感谢任何帮助。
答案 0 :(得分:0)
如果我做得对,你应该在[Orders From External Calls]
定义中使用CASE语句:
SELECT T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
Count(T_Temp_RestrictedProductSalesHistory.CustomerCode) AS [Orders Taken],
sum( CASE WHEN <Your condition here>
THEN 1
ELSE 0
END) AS [Orders From External Calls]
FROM T_Temp_RestrictedDiaryCalls
INNER JOIN T_Temp_RestrictedProductSalesHistory
ON (T_Temp_RestrictedDiaryCalls.CustomerCode = T_Temp_RestrictedProductSalesHistory.CustomerCode)
AND (T_Temp_RestrictedDiaryCalls.CallDate = T_Temp_RestrictedProductSalesHistory.EntryDate)
GROUP BY T_Temp_RestrictedDiaryCalls.AccreditedDomainCode;
答案 1 :(得分:0)
如果我理解正确,您希望这两个Orders
列都计算来自同一个表的数据,但对表中的哪些记录进行计数以及哪些记录不计数有不同的限制。所以做一些像:
SELECT T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
Count(SalesHistoryForAllOrders.CustomerCode) AS [Orders Taken],
Count(SalesHistoryForExternalOrders.CustomerCode) AS [Orders From External Calls]
FROM T_Temp_RestrictedDiaryCalls
INNER JOIN T_Temp_RestrictedProductSalesHistory SalesHistoryForAllOrders
ON (T_Temp_RestrictedDiaryCalls.CustomerCode = SalesHistoryForAllOrders.CustomerCode)
AND (T_Temp_RestrictedDiaryCalls.CallDate = SalesHistoryForAllOrders.EntryDate)
INNER JOIN T_Temp_RestrictedProductSalesHistory SalesHistoryForExternalOrders
ON (T_Temp_RestrictedDiaryCalls.CustomerCode = SalesHistoryForExternalOrders.CustomerCode)
AND (T_Temp_RestrictedDiaryCalls.CallDate = SalesHistoryForExternalOrders.EntryDate)
GROUP BY T_Temp_RestrictedDiaryCalls.AccreditedDomainCode;
通过INNER连接表格两次并且每次别名,我们现在有两个单独的表格表示(称为SalesHistoryForAllOrders
和SalesHistoryForExternalOrders
)。
然后,您可以自由地放置一个WHERE子句,该子句分别引用其中任何一个,并且它只会影响该列,而不会影响另一个列。所以要么:
WHERE SalesHistoryForExternalOrders.IsAnExternalOrder > 0
或者只是在第二个INNER JOIN中添加一个AND:
AND SalesHistoryForExternalOrders.IsAnExternalOrder > 0
,结果相同:该子句仅应用于External Calls
列。
答案 2 :(得分:0)
根据您在评论中所说的内容,一列可能包含所有行的计数,而其他列只显示指定大小写的值。
所以:
select table1.a,count(table1.b),
(select count(table2.c) from table2 where "where clause")
from table1