2013-04-29 39 views
1

表填充爲不太重要的值的摘要如下T-SQL表加一排,

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

我想查詢其中將列出的銷售值,我所有的客戶,如果值(每客戶)超過1000如果是少的話,我只是想看到一個摘要行表明所有客戶的總價值< = 1000。結果會是這個樣子:提前

CusE       2500 
CusD       1200 

(Small Value Customers)  1250 

Total       4950 

感謝。

回答

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 

DEMO

+0

CTE和選擇對我來說似乎沒有必要。 – Diego 2013-04-29 13:04:44

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 
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 

sqlfiddle

+0

這將產生SUM和只返回一行,OP已經表示他們希望所有客戶都顯示在總數 – 2013-04-29 12:41:51

+0

我已經介紹union – 2013-04-29 12:45:57

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

或者如果你不能用ROLLUP操作中使用GROUP BY子句

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