将查询从MS Access转换为SQL Server

时间:2017-05-10 11:53:17

标签: sql sql-server ms-access

我对SQL的经验有限,但我被要求从MS Access转换以下查询。

TRANSFORM SUM(weekpace_crosstab.wgt) AS SumOfwgt
    SELECT 
        Products.[Product Type], SUM(weekpace_crosstab.wgt) AS DeliveryTotal    
    FROM 
        (weekpace_crosstab 
    LEFT JOIN 
        Customer ON weekpace_crosstab.Customer = Customer.Customer)  LEFT JOIN Products ON weekpace_crosstab.Product = Products.[Product Code]
WHERE (((Customer.[Customer Group])="Sainsbury"))
GROUP BY Products.[Product Type]
PIVOT weekpace_crosstab.Date;

这是结果......

通过谷歌和本论坛的其他问题,我写了以下声明。但是,我无法将交付总额显示在上图中。

SELECT * FROM 
(
SELECT P.[Product Type], wc.Date, sum (wc.wgt) AS DeliveryTotal

FROM weekpace_crosstab AS wc LEFT JOIN Customer AS C ON wc.Customer = C.Customer LEFT JOIN Products as p 

ON wc.Product = P.[Product Code]

WHERE C.[Customer Group]='Co-op'

GROUP BY  p.[Product Type], wc.Date, wc.wgt
) AS s
PIVOT 
(
SUM (DeliveryTotal)
FOR [Date] in ([2017-01-23],[2017-01-24],[2017-01-25],[2017-01-26],[2017-01-27],[2017-01-28],[2017-01-29])
)AS pvt
ORDER BY [Product Type]

以下是此查询的结果...

有人可以建议如何添加交付总栏数吗?

感谢您的关注。

1 个答案:

答案 0 :(得分:1)

您需要将DeliveryTotal作为第二列添加,因为第一列将由枢轴使用,它将仅显示已旋转

尝试

SELECT * FROM 
(
SELECT P.[Product Type], wc.Date, sum (wc.wgt) AS DeliveryTotal, w.wgt
FROM weekpace_crosstab AS wc LEFT JOIN Customer AS C ON wc.Customer = 
C.Customer LEFT JOIN Products as p 

ON wc.Product = P.[Product Code]
LEFT JOIN (
SELECT SUM(wgt)wgt, Product 
FROM weekpace_crosstab 
WHERE Date IN ('2017-01-23', '2017-01-24', '2017-01-25', '2017-01-26', '2017-01-
27', '2017-01-28', '2017-01-29')
GROUP BY product) w ON w.Product = wc.product

WHERE C.[Customer Group]='Co-op'

GROUP BY  p.[Product Type], wc.Date, w.wgt
) AS s
PIVOT 
(
SUM (DeliveryTotal)
FOR [Date] in ([2017-01-23],[2017-01-24],[2017-01-25],[2017-01-26],[2017-01-
27],[2017-01-28],[2017-01-29])
)AS pvt
ORDER BY [Product Type]