下表的SQL命令

时间:2010-04-16 03:49:43

标签: sql sql-server

我有一个名为“Sales”的表,其中包含以下列:

Sales_ID|Product_Code|Zone|District|State|Distributor|Total_Sales

现在我想生成一个销售摘要,按区域查看总销售额,然后按地区查看,然后按国家/地区查看上一个/上个月期间的分销商。

如何编写Sql语句来执行此操作?任何人都可以帮助我Plz。提前谢谢。

我还有另一个问题,如何从表格的任何一列中选择第二大或第三大值。

2 个答案:

答案 0 :(得分:3)

请查看使用ROLLUP GROUP BY选项。

Generates the simple GROUP BY aggregate rows, plus subtotal or super-aggregate rows,
and also a grand total row.

The number of groupings that is returned equals the number of expressions 
in the <composite element list> plus one. For example, consider the following statement.

    Copy Code 
    SELECT a, b, c, SUM ( <expression> )
    FROM T
    GROUP BY ROLLUP (a,b,c)

One row with a subtotal is generated for each unique combination of values of 
(a, b, c), (a, b), and (a). A grand total row is also calculated. 

Columns are rolled up from right to left. 
The column order affects the output groupings of ROLLUP and can affect the number 
of rows in the result set.

这样的东西
DECLARE @Table TABLE(
        Zone VARCHAR(10),
        District VARCHAR(10),
        State VARCHAR(10),
        Sales FLOAT
)

INSERT INTO @Table SELECT 'A','A','A',1
INSERT INTO @Table SELECT 'A','A','B',1
INSERT INTO @Table SELECT 'A','B','A',1
INSERT INTO @Table SELECT 'B','A','A',1

SELECT  Zone,
        District,
        State,
        SUM(Sales)
FROM    @Table
WHERE <Your Condition here> --THIS IS WHERE YOU USE THE WHERE CLAUSE
GROUP BY ROLLUP (Zone,District,State)

要获得第二个和第三个,您可以使用(ROW_NUMBER (Transact-SQL)

;WITH Vals AS (
        SELECT  *,
                ROW_NUMBER() OVER (ORDER BY RequiredCol DESC) RowNum
        FROM    YourTable
)
SELECT  *
FROM    Vals
WHERE   RowNum IN (2,3)

SELECT  TOP 2
        *
FROM    (
            SELECT  TOP 3
                    *
            FROM    YourTable
            ORDER BY RequiredCol DESC
        ) sub
ORDER BY RequiredCol

答案 1 :(得分:0)

SELECT SUM(Total_Sales) FROM sales GROUP BY (X)

将X替换为ZoneDistrictStateDistributor