SQL EXCEPT不工作

时间:2014-12-10 14:50:05

标签: sql-server tsql

; WITH cte AS
(SELECT p.BudgetNumber, t.MilestoneNumber FROM
(SELECT DISTINCT BudgetNumber FROM tblMilestones) p 
CROSS JOIN
(SELECT DISTINCT MilestoneNumber FROM tblMilestoneTemplate) t)

SELECT BudgetNumber, MilestoneNumber FROM cte 
EXCEPT (SELECT BudgetNumber, MilestoneNumber FROM tblMilestones)
ORDER BY BudgetNumber, MilestoneNumber 

上面的查询使用交叉连接创建所有可能的BudgetNumber和MilestoneNumber组合,然后尝试查找不在tblMilestones表中的组合(我没有创建此数据库,我知道表前缀很奇怪,这个db没有被标准化)。

其中任何一个字段都没有NULL条目。当我使用上面的EXCEPT子句的这个查询时,我得到一些缺失值(但不是全部),但我也得到一些非缺失值。当我将EXCEPT更改为LEFT JOIN时,我得到相同的结果。当我将EXCEPT更改为WHERE NOT EXISTS时,我根本没有得到任何结果。有人可以帮忙吗?

SQLFiddle Output

| BUDGETNUMBER | MILESTONENUMBER |
|--------------|-----------------|
|      BA04001 |               0 |
|      BA04001 |              99 |
|      BA04005 |               0 |
|      BA04005 |              99 |
|      BA05001 |               0 |
|      BA05001 |              99 |
|      BA05002 |               0 |
|      BA05002 |              99 |

1 个答案:

答案 0 :(得分:1)

以下是正确使用NOT EXISTS的方法。您需要在子查询中指定where子句以获得正确的结果。

;
WITH    cte
          AS (
               SELECT p.BudgetNumber
                   ,t.MilestoneNumber
                FROM (
                       SELECT DISTINCT BudgetNumber
                        FROM tblMilestones
                     ) p
                CROSS JOIN (
                             SELECT DISTINCT MilestoneNumber
                                FROM tblMilestoneTemplate
                           ) t
             )
    SELECT BudgetNumber
           ,MilestoneNumber
        FROM cte t
        WHERE NOT EXISTS ( SELECT 1
                            FROM tblMilestones s
                            WHERE t.BudgetNumber = s.BudgetNumber
                                AND t.MilestoneNumber = s.MilestoneNumber )
        ORDER BY BudgetNumber
           ,MilestoneNumber 

请看以下两个例子

DECLARE @NoPrecision AS TABLE ( MyNumber DECIMAL )
INSERT INTO @NoPrecision ( MyNumber ) VALUES ( 12345.123456789 )
SELECT * FROM @NoPrecision

输出:12345

DECLARE @Precision AS TABLE ( MyNumber DECIMAL(10,4) )
INSERT INTO @Precision ( MyNumber ) VALUES ( 12345.123456789 )
SELECT * FROM @Precision

输出:12345.1235