1

表格填充如下

CustomerName                  SalesValue
CusA                          100
CusB                          250
CusC                          900
CusD                          1200
CusE                          2500

我想要一个查询,如果值(每个客户)超过 1000,它将列出我所有客户的销售值。如果它更小,那么我只想看到一个汇总行,指示所有客户的总价值 <= 1000。结果会看起来像这样:

CusE                          2500
CusD                          1200

(Small Value Customers)       1250

Total                         4950

提前致谢。

4

4 回答 4

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

演示

于 2013-04-29T12:40:44.383 回答
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
于 2013-04-29T12:32:00.403 回答
0

here is the query

 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

and sqlfiddle

于 2013-04-29T12:39:16.387 回答
0

带有GROUP BY ROLLUP的 SQLServer2008+ 选项

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
于 2013-04-29T13:20:32.260 回答