将Access TRANSFORM / PIVOT查询转换为SQL Server 2012

时间:2015-03-30 16:29:46

标签: ms-access sql-server-2012

我需要帮助将此MS Access查询转换为SQL Server 2012:

TRANSFORM 
SUM(TTQTY * qty) AS quantity 
SELECT matlprodcode AS product_code, cvend_name AS supplier, CITMCD AS material, matldesc AS description, MIN(unit_cost) AS unit_cost 
FROM acs_Budget 
WHERE matlprodcode NOT LIKE ';I8*' 
AND matlprodcode NOT LIKE 'I1' 
GROUP BY matlprodcode, cvend_name, CITMCD, matldesc 
PIVOT budgetmonth;

我在这里尝试过转换它:

SELECT matlprodcode AS product_code, 
    cvend_name AS supplier, 
    CITMCD AS material, 
    matldesc AS 'description', 
    MIN(unit_cost) AS unit_cost 
FROM
(
   SELECT TTQTY, qty, matlprodcode, cvend_name, CITMCD, matldesc, unit_cost, budgetmonth FROM acs_Budget WHERE matlprodcode NOT LIKE ';I8*' AND matlprodcode NOT LIKE 'I1' 
) AS T
PIVOT
(
   SUM(TTQTY * qty)
) P

这是对的吗?有什么建议?或者我离开了?

1 个答案:

答案 0 :(得分:1)

我自己想通了。我不确定这是否会对其他人有所帮助,但这里是最终查询将在SQL Server中工作。我从MS Access转换了这个:

SELECT pt.* FROM 
(SELECT SUM(TTQTY * qty) AS quantity, matlprodcode AS product_code, cvend_name AS supplier, CITMCD as material, matldesc AS description, MIN(unit_cost) AS unit_cost, budgetmonth 
FROM acs_Budget 
WHERE matlprodcode NOT LIKE ';I8*' 
AND matlprodcode NOT LIKE 'I1' 
GROUP BY matlprodcode, cvend_name, CITMCD, matldesc, budgetmonth) AS src 
PIVOT (MIN(quantity) FOR src.budgetmonth IN ([4/1/2015], [5/1/2015], [6/1/2015], [7/1/2015], [8/1/2015], [9/1/2015], [10/1/2015], [11/1/2015], [12/1/2015], [1/1/2016], [2/1/2016], [3/1/2016])) AS pt;

一些帮助我的事情:

  • 首先,我选择了我想看到的一切。包括MS Access正在转换和转动的内容。
  • 然后我发现MS Access每个列都在转动,在这种情况下是数量。
  • 所以我做了数量的MIN,因为PIVOT需要一个聚合函数。
  • 在聚合函数之后,您需要MS Access正在使用的实际PIVOT,它位于FOR之后。
  • 然后我做了一些类似于SELECT DISTINCT预算单从FROM acs_Budget获得的东西,以获得我可以转动的每个项目,这就是IN进来的地方。

不确定我是否解释得很好,但这就是我的工作方式!