希望对你有帮助
SELECT *
FROM
(
SELECT productName,
[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29],[30], [31]
FROM
(
SELECT productName, day(pDate) AS dayOfDate, sum(quantity) AS Qty
FROM [yourTableName] --Enter here your table name]
WHERE -- Use this to display data for July 2013.
Month(pDate) = 7 and YEAR(pDate) = 2013
GROUP BY productName, day(pDate)
) AS tempTable
PIVOT
(sum(Qty) FOR dayOfDate IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29],[30], [31])) as Qty
) AS detailTable,
(
SELECT productName, sum(quantity) as TOTAL
FROM [yourTableName] --Enter here your table name]
WHERE -- Use this to display data for July 2013.
Month(pDate) = 7 and YEAR(pDate) = 2013
GROUP BY productName
) AS totalTable
WHERE totalTable.productName = detailTable.productName
我已经在 ADVENTUREWORKS 数据库上对其进行了测试。我使用了以下查询:
SELECT *
FROM
(
SELECT productid,
[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29],[30], [31]
FROM
(
SELECT productid, day(Modifieddate) AS dayOfDate, sum(Orderqty) AS Qty
FROM Sales.SalesOrderDetail --Enter here your table name
WHERE -- Use this to display data for February 2004.
Month(ModifiedDate) = 2 and YEAR(ModifiedDate) = 2004
GROUP BY productid, day(Modifieddate)
) AS tempTable
PIVOT
(sum(Qty) FOR dayOfDate IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29],[30], [31])) as Qty
) AS detailTable,
(
SELECT productid, sum(Orderqty) as TOTAL
FROM Sales.SalesOrderDetail
WHERE -- Use this to display data for February 2004.
Month(ModifiedDate) = 2 and YEAR(ModifiedDate) = 2004
GROUP BY productid
) AS totalTable
WHERE totalTable.ProductID = detailTable.ProductID