我一直在讨论这个问题,并认为有人可能有一个聪明的方法来解决我的问题。我按类别成员资格查询销售情况,如果客户是单个销售类别的成员,则需要汇总所有销售。例如:
Cust Category Sale
A Pie 3
A Cake 5
B Pie 4
C Cake 8
C Limes 1
在示例中,我想获得任何类别='Cake'的总销售额,结果是:
Cust Sale
A 8
C 9
我一直在写两个查询(或子查询),但想知道是否有一个我错过的直接方法。当然,真实数据更复杂,但这是我想要完成的要点。有关如何有效地做到这一点而不进行次要考虑的任何想法?
答案 0 :(得分:0)
Select A.Cust, A.Category, B.SumSale
from Sales A
Where A.Category like '%Cake%'
Left Join
(Select Cust, Category, Sum(Sale) as SumSale
from Sales
Group By Cust, Category) B
On B.Cust = A.Cust
答案 1 :(得分:0)
CTE也可以:
WITH cte AS
(
SELECT Cust FROM demo
WHERE Category = 'Cake'
)
SELECT cte.Cust, SUM(Sale) AS Sales FROM demo
JOIN cte ON cte.Cust = demo.Cust
GROUP BY cte.Cust
答案 2 :(得分:0)
您可以在WHERE子句
中使用带有相关子查询的EXISTS运算符SELECT t1.Cust, SUM(t1.Sale) AS Sale
FROM dbo.test134 t1
WHERE EXISTS (
SELECT 1
FROM dbo.test134 t2
WHERE t1.Cust = t2.Cust
AND t2.Category = 'Cake'
)
GROUP BY t1.Cust
或者使用SQLServer2005 +的OVER子句聚合函数
;WITH cte AS
(
SELECT Cust, Category, SUM(Sale) OVER(PARTITION BY Cust) AS Sale
FROM dbo.test134
)
SELECT *
FROM cte
WHERE Category = 'Cake'
查看两个查询的演示SQLFiddle
答案 3 :(得分:-1)
类似的东西:
SELECT Category, Sum(Sales) AS [Sale Totals]
FROM tblSales
GROUP BY Category
编辑:如果您想按所有类别进行分组,而不仅仅是“蛋糕”,这是适用的。 编辑2:但是,如果您只想要一个类别,只需添加一个简单的:
WHERE Category = 'Cake'
在FROM和GROUP BY行之间。