比较当月与上个月的销售额 - 功能 - T-SQL

时间:2017-05-21 19:04:05

标签: sql-server function tsql subquery

我创建了一个SalesMonth函数,该函数接收月份编号和年份编号作为参数,并显示一个总计列表,其中包含作为参数传递的月份和年份中销售的产品。该列表显示以下产品信息:标识符,月份,年份,总销售数量,平均单价,已授予的总折扣和已售出的总价值。

请遵循以下代码:

CREATE FUNCTION SalesMonth (@month int, @year int)
RETURNS TABLE
AS
RETURN (
    SELECT
        AdventureWorks.Sales.SalesOrderDetail.ProductID,
        MONTH(AdventureWorks.Sales.SalesOrderHeader.OrderDate) as 'Mes',
        YEAR(AdventureWorks.Sales.SalesOrderHeader.OrderDate) as 'Ano',
        SUM(AdventureWorks.Sales.SalesOrderDetail.OrderQty) as 'Quantidade Total Vendida',
        AVG(AdventureWorks.Sales.SalesOrderDetail.UnitPrice) as 'Preco Unitario Médio',
        SUM(AdventureWorks.Sales.SalesOrderDetail.UnitPriceDiscount) as 'Desconto Total',
        SUM(AdventureWorks.Sales.SalesOrderDetail.LineTotal) as 'Valor Total Vendido'
    FROM
        AdventureWorks.Sales.SalesOrderDetail
    INNER JOIN
        AdventureWorks.Sales.SalesOrderHeader
    ON
        AdventureWorks.Sales.SalesOrderHeader.SalesOrderID = AdventureWorks.Sales.SalesOrderDetail.SalesOrderID
    WHERE 
        MONTH(AdventureWorks.Sales.SalesOrderHeader.OrderDate) = @month
            AND
        YEAR(AdventureWorks.Sales.SalesOrderHeader.OrderDate) = @year
    GROUP BY
            AdventureWorks.Sales.SalesOrderDetail.ProductID,
            MONTH(AdventureWorks.Sales.SalesOrderHeader.OrderDate),
            YEAR(AdventureWorks.Sales.SalesOrderHeader.OrderDate)
)

现在我需要比较哪些项目的销售额与上个月相比有所增长。我想做类似的事情:

SELECT * 
FROM SalesMonth(10, 2001) 
WHERE SumPrice > (SELECT SumPrice FROM SalesMonth(9, 2001))

我知道这是一个严重错误,但我想不出类似的东西。有人会对这个问题有类似的查询吗?

2 个答案:

答案 0 :(得分:0)

将第10个月的销售额与第9个月的销售额挂钩。

I am very #happy man but my wife is not 
I am very #happy man but     my wife   is not     
I am very #happy man but ##  ##  my wife ##  is not  ##  ## 

答案 1 :(得分:0)

您可以尝试按以下方式加入访问:

['entry', 1, 'entrya', 5, 'anotherentry', 7, 'entryb', 10, 'entryd', 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]