有多种方法可以产生您想要的结果。这个使用 CTE 计算两个月的总数,然后将其连接回自身。
With cte as
(
SELECT
o.productname,
Datepart(month, datetimereceived) m,
Count(*) AS totalSales
FROM order o
INNER JOIN product p
ON o.productid = p.productid
WHERE Datepart(month, datetimereceived) in ( 2, 2-1)
AND Datepart(year, datetimereceived) = 2012
GROUP BY o.productname,
Datepart(month, datetimereceived)
ORDER BY totalsales DESC )
SELECT
a.productName ,
a.totalSales,
a.totalSales / b.totalSales percentage_of_prevous_month
FROM
cte a
INNER JOIN cte b
ON a.productname = b.productname
and a.month = b.month - 1
There are some pieces missing. You'll probably actually need to do something like to get a non zero value, if the division results in a number < 0
cast(a.totalSales as decimal)/ cast( b.totalSales as decimal)
Also the using the Month input like this will cause problems if your input is January. So you're better of normalizing the datetimerecived to the first of the month
e.g.
Modified SELECT and Group by
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)-1),datetimerecieved),101) m
Modified WHERE
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(datetimerecieved)-1),datetimerecieved),101)
in ( '2/1/2012', DateAdd(m,-1,'2/1/2012'))
Modified ON
a.M > b.M