2012-08-06 144 views
3

我有按預期正常運行下面的查詢:SQL查詢工作在SQL Server中,無法在Excel(Microsoft查詢)

SELECT 
     SERVICE_HISTORY.ServiceMode, SERVICE_HISTORY.CreatedDate, 
     SERVICE_HISTORY.CreatedBy, SERVICE_HISTORY.Branch, 
     SERVICE_HISTORY.Comments 
FROM 
     DEBA_US.dbo.SERVICE_HISTORY 
JOIN 
     (SELECT MAX(SERVICE_HISTORY.CreatedDate) AS maxDate, CUSTOMER.AccNo 
     FROM DEBA_US.dbo.CUSTOMER 
     INNER JOIN (DEBA_US.dbo.SERVICE_HISTORY 
        INNER JOIN DEBA_US.dbo.CAR ON SERVICE_HISTORY.ROW_PK = CAR.ROW_PK) ON CUSTOMER.ROW_PK = CAR.ROW_PK 
     WHERE 
      CUSTOMER.AccNo LIKE 'CUS-1234' 
      AND CAR.DateSubmitted IS NULL 
     GROUP BY 
      CUSTOMER.AccNo) AS testQuery ON testQuery.maxDate = SERVICE_HISTORY.CreatedDate 

查詢是給我的最新(最大)的服務歷史日期爲給予客戶。

當我執行在SQL Server查詢,其工作完全正常,但是當我把同一個查詢到的Excel 2010(Microsoft查詢),它給我的錯誤:

No Column name was specified for Column 1 of 'testQuery'
Invalid column name 'maxDate'
Statement could not be prepared

我不能修復查詢以通過錯誤。有人可以告訴我爲什麼Excel不能處理上述查詢嗎?由於

+0

我通常會發現MS查詢是相當有限的,所以我通常會通過製作視圖來簡化我向MS Query提供的內容。如果我想要做的事情對於視圖來說過於複雜,我將創建一個返回數組的VBA UDF。 – 2013-02-01 14:05:38

回答

4

你需要把testQuery和的maxDate單引號

SELECT 
    SERVICE_HISTORY.ServiceMode, SERVICE_HISTORY.CreatedDate, 
    SERVICE_HISTORY.CreatedBy, SERVICE_HISTORY.Branch, 
    SERVICE_HISTORY.Comments 
FROM 
    DEBA_US.dbo.SERVICE_HISTORY 
JOIN 
    (SELECT MAX(SERVICE_HISTORY.CreatedDate) AS 'maxDate', CUSTOMER.AccNo 
    FROM DEBA_US.dbo.CUSTOMER 
    INNER JOIN (DEBA_US.dbo.SERVICE_HISTORY 
       INNER JOIN DEBA_US.dbo.CAR ON SERVICE_HISTORY.ROW_PK = CAR.ROW_PK) ON  CUSTOMER.ROW_PK = CAR.ROW_PK 
    WHERE 
     CUSTOMER.AccNo LIKE 'CUS-1234' 
     AND CAR.DateSubmitted IS NULL 
    GROUP BY 
     CUSTOMER.AccNo) AS 'testQuery' ON testQuery.maxDate = SERVICE_HISTORY.CreatedDate 
2

你需要做的唯一的事情是添加各地的maxDate方括號像以下:

SELECT 
     SERVICE_HISTORY.ServiceMode, SERVICE_HISTORY.CreatedDate, 
     SERVICE_HISTORY.CreatedBy, SERVICE_HISTORY.Branch, 
     SERVICE_HISTORY.Comments 
FROM 
     DEBA_US.dbo.SERVICE_HISTORY 
JOIN 
     (SELECT MAX(SERVICE_HISTORY.CreatedDate) AS [maxDate], CUSTOMER.AccNo 
     FROM DEBA_US.dbo.CUSTOMER 
     INNER JOIN (DEBA_US.dbo.SERVICE_HISTORY 
        INNER JOIN DEBA_US.dbo.CAR ON SERVICE_HISTORY.ROW_PK = CAR.ROW_PK) ON CUSTOMER.ROW_PK = CAR.ROW_PK 
     WHERE 
      CUSTOMER.AccNo LIKE 'CUS-1234' 
      AND CAR.DateSubmitted IS NULL 
     GROUP BY 
      CUSTOMER.AccNo) AS testQuery ON testQuery.maxDate = SERVICE_HISTORY.CreatedDate