我有两个想要联合在一起的查询(包含一些临时表)。当我用联盟注释掉一个(无关紧要的)查询时,它可以工作。但是当我介绍工会时,我得到The ntext data type cannot be selected as DISTINCT because it is not comparable.
我不明白为什么,因为这两个主要查询都不使用。主要选择参考:
SELECT
dbo.CUSTTABLE.ACCOUNTNUM AS 'Account Number',
dbo.CUSTTABLE.NAME AS 'Customer Name',
[DESCRIPTION] AS 'Division',
ISNULL(dbo.USERINFO.NAME, 'OPEN') AS 'Sales Engineer',
[STATE],
PHONE,
PAYMTERMID AS 'Terms',
(CASE BLOCKED
WHEN 0 THEN 'No'
WHEN 2 THEN 'Financial Hold'
WHEN 1 THEN 'System Hold'
ELSE 'Unknown' END) AS 'Status',
[45-60],
[61-90],
[91-120],
[120+],
#temptable2.Today,
ISNULL(USERMEMO, '') AS 'Notes',
ISNULL(#temptable2.Today / NULLIF((ISNULL(#salesTemp.PQ1, 0) / 90), 0),0) AS 'DSO1',
CustTable.StatisticsGroup as 'Past Due Category'
FROM
dbo.CUSTTABLE INNER JOIN
dbo.DIMENSIONS ON DIMENSION2_ = NUM INNER JOIN
#temptable2 ON dbo.CUSTTABLE.ACCOUNTNUM = #temptable2.ACCOUNTNUM LEFT OUTER JOIN
#temptable ON dbo.CUSTTABLE.ACCOUNTNUM = #temptable.ACCOUNTNUM LEFT OUTER JOIN
dbo.SMMSALESUNITMEMBERS ON SALESGROUP = SALESUNITID AND SALESMANAGER = 1 LEFT OUTER JOIN
dbo.USERINFO ON ID = SALESMANID AND [ENABLE] = 1
JOIN #salesTemp on #salesTemp.ACCOUNTNUM = CUSTTABLE.ACCOUNTNUM
WHERE
DIMENSION2_ IN (@division)
UNION
SELECT
Customer_ID AS 'Account Number',
Customer_Name AS 'Customer Name',
'South Bend' AS Division,
'' AS 'Sales Engineer',
'Indiana' AS 'State',
'' AS 'Phone',
Customer_Terms AS 'Terms',
'' AS 'Status',
[45-60],
[61-90],
[91-120],
[120+],
[Today],
'' AS 'Notes',
'' AS 'DSO1',
'' AS 'Past Due Category'
FROM #temptable4
答案 0 :(得分:6)
更改:'' AS 'DSO1',
至
NULL as 'DS01',
空集不能在SQL服务器中转换为数字;这是根据联合的顶部选择中定义的数据类型所必需的。
我认为这是问题所在,因为联合中的顶部选择将返回一个数值。由于空集不能转换为数字,因此要么提供数字(0)要么使用null。
在执行union时请记住,列数必须匹配且其数据类型必须匹配。如果他们没有收到这样的错误。
关于评论,"我不明白为什么,因为这两个主要查询都没有使用不同的" UNION
对生成的联合结果执行不同的操作。 UNION ALL
不会。这就是执行UNION ALL
执行速度更快的原因,因为它必须执行UNION
执行中包含的重复删除。