SQL Server int转换忽略子查询?

时间:2014-12-06 17:20:27

标签: sql-server

我的数据库中有两个表。其中一个包含邮政编码位置的货件数据,另一个表格包含美国所有拉链的完整邮政编码清单。我刚刚在下面列出了相关专栏,以保持简单。

表:ZipCodes

  • ZipCode PK char(5)

表:货件

  • ShipToZip varchar(10)
  • AMT小数(10,2)

因此,某些货件数据可能是非美国地址,其他货物可能包含+4美国邮政编码(XXXXX-XXXX),这就是货件表最多为10的原因。我需要做的就是将查询导出为CSV,但我需要将邮政编码转换为整数。

SELECT CAST(ShipToZIP AS INT) AS [target],SUM(cast(AMT as int)) AS [total]
FROM
    (SELECT LEFT(ShiptoZip,5) ShipToZip,Amt
        FROM Shipments
        WHERE LEFT(SHIPTOZIP,5) IN (SELECT zipcode from ZipCodeLocations)
    ) Q
GROUP BY CAST(ShipToZIP AS INT)

但是,当我运行该查询时,我不断收到加拿大邮政编码的转换错误。如果我自己运行内部Q查询,则每个记录都是有效的仅限美国的代码。

如何强制子查询先运行?我尝试按this post进行CTE,但它也无法正常工作。

1 个答案:

答案 0 :(得分:1)

问题是执行计划,我不确定你是否可以强制子查询运行1st。

您可以执行此操作并防止必须CAST到INT。

SELECT CASE ShiptoZip WHEN LEFT(ShiptoZip) = '0' THEN RIGHT(ShiptoZip, LEN(ShiptoZip) - 1) ELSE ShiptoZip END AS [target],
SUM(cast(AMT as int)) AS [total]
FROM
  (SELECT LEFT(ShiptoZip,5) ShipToZip,Amt
    FROM Shipments
    WHERE LEFT(SHIPTOZIP,5) IN (SELECT zipcode from ZipCodeLocations)
  ) Q
GROUP BY CASE ShiptoZip WHEN LEFT(ShiptoZip) = '0' THEN RIGHT(ShiptoZip, LEN(ShiptoZip) - 1) ELSE ShiptoZip END

如果您必须走这条路线,那么您的另一个选择是在聚合后CAST到INT。

SELECT CAST(ShipToZIP AS INT) AS [target],[total]
FROM
(SELECT LEFT(ShiptoZip,5) ShipToZip, SUM(cast(AMT as int)) AS [total]
    FROM Shipments
    WHERE LEFT(SHIPTOZIP,5) IN (SELECT zipcode from ZipCodeLocations)
    GROUP BY ShipToZIP
) Q