1

テーブルは次のように入力されます

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

値 (顧客ごと) が 1000 を超える場合に、すべての顧客の売上値をリストするクエリが必要です。それよりも小さい場合は、すべての顧客の合計値 <= 1000 を示す 1 つの集計行を表示したいだけです。結果は次のようになります。次のようになります。

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

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 のデモ

または 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
于 2013-04-29T13:20:32.260 に答える