表格填写如下
CustomerName SalesValue
CusA 100
CusB 250
CusC 900
CusD 1200
CusE 2500
我想要一个查询,如果价值(每位客户)超过1000,我会列出所有客户的销售价值。如果它少了,那么我只想看到一个汇总行,表明所有客户的总价值客户< = 1000.结果看起来像这样:
CusE 2500
CusD 1200
(Small Value Customers) 1250
Total 4950
提前致谢。
答案 0 :(得分:3)
也许:
WITH sales AS
(
SELECT [CustomerName], [SalesValue],
CustSales = SUM(SalesValue)OVER(PARTITION BY CustomerName)
FROM dbo.Sales
)
SELECT CustomerName, CustSales FROM(
SELECT 1 AS Source,
CustomerName,
CustSales = SUM(CustSales) FROM sales
GROUP BY CustomerName
HAVING SUM(CustSales) > 1000
UNION ALL
SELECT 2 As Source,
CustomerName = '(Small Value Customers)',
CustSales = SUM(CustSales) FROM sales
WHERE CustSales <= 1000
UNION ALL
SELECT 3 As Source,
CustomerName = 'Total',
CustSales = SUM(CustSales) FROM sales
) AS X
ORDER BY X.Source, X.CustSales DESC
答案 1 :(得分:1)
你可以这样做:
DECLARE @LargeCustomersSum INT
SELECT @LargeCustomersSum = SUM(SalesValue)
FROM YourTable
WHERE SalesValue >= 1000
DECLARE @SmallCustomersSum INT
SELECT @SmallCustomersSum = SUM(SalesValue)
FROM YourTable
WHERE SalesValue <= 1000
SELECT 'Large Value Customers', @LargeCustomersSum
UNION
SELECT CustomerName, SalesValue
FROM YourTable
ORDER BY SalesValue DESC
WHERE SalesValue >= 1000
UNION
SELECT 'Small Value Customers', @SmallCustomersSum
UNION
SELECT CustomerName, SalesValue
FROM YourTable
ORDER BY SalesValue DESC
WHERE SalesValue <= 1000
UNION
SELECT 'Total', @LargeCustomersSum + @SmallCustomersSum
答案 2 :(得分:0)
这是查询
select SalesValue, CustomerName from cus_sales where SalesValue > 1000
UNION
select sum(SalesValue) as Sum, 'Others' as CustomerName from cus_sales where SalesValue <= 1000
UNION
select sum(SalesValue) as Sum, 'Total' as CustomerName from cus_sales
答案 3 :(得分:0)
SQLServer2008 +的选项GROUP BY ROLLUP
SELECT ISNULL(CASE WHEN SalesValue > 1000 THEN CustomerName
ELSE 'SmallValueCustomers' END, 'Total') AS CustomerName,
SUM(SalesValue) AS SumSalesValue
FROM dbo.sales
GROUP BY ROLLUP(CASE WHEN SalesValue > 1000 THEN CustomerName
ELSE 'SmallValueCustomers' END)
SQLFiddle上的演示
OR如果不能将GROUP BY子句与ROLLUP操作一起使用
SELECT CASE WHEN SalesValue > 1000 THEN CustomerName
ELSE 'SmallValueCustomers' END AS CustomerName,
SUM(SalesValue) AS SumSalesValue
FROM dbo.sales
GROUP BY CASE WHEN SalesValue > 1000 THEN CustomerName
ELSE 'SmallValueCustomers' END
UNION ALL
SELECT 'Total', SUM(SalesValue)
FROM dbo.sales