Access / SQL Union

时间:2013-06-03 14:31:31

标签: sql database ms-access-2007

SELECT Campaign, Prem1Item, Prem1Qty, Prem1Drop, Prem2Item, Prem2Qty, Prem2Drop, Prem3Item, Prem3Qty, Prem3Drop, Prem4Item, Prem4Qty,  Prem4Drop, Prem5Item, Prem5Qty, Prem5Drop, Prem10ItemPkging, AckLtr1TypeCode, AckLtr10ItemPkging, ContactID
    FROM [TU FAR Before VB]
UNION ALL 
SELECT Campaign, Prem6Item, Prem6Qty, Prem6Drop, Prem7Item, Prem7Qty, Prem7Drop, Prem8Item, Prem8Qty, Prem8Drop, Prem9Item, Prem9Qty, Prem9Drop, NULL, NULL, NULL, Prem10ItemPkging, NULL, AckLtr10ItemPkging, ContactID
FROM [TU FAR Before VB]
WHERE NOT
 (
    (Prem6Item IS NULL) AND (Prem7Item IS NULL) AND (Prem8Item IS NULL)
     AND (Prem9Item IS NULL)
 );

在上面的代码中,一切都很好我只需要为名为Continued的表添加一个字段,该字段等于"Y",因为它有超过5个项目而创建的所有记录和"N"所有包含前5项的记录。

我想知道是否有办法在不必完全制作新表的情况下执行此操作?

提前感谢您对此事的任何帮助。

1 个答案:

答案 0 :(得分:2)

您只需在每个查询中添加一个硬编码列:

SELECT  ....,
        'N' AS Continued
FROM    ...
UNION ALL
SELECT  ....,
        'Y' AS Continued
FROM    ...

因此,您的完整查询将成为:

SELECT  Campaign, 
        Prem1Item, 
        Prem1Qty, 
        Prem1Drop, 
        Prem2Item, 
        Prem2Qty, 
        Prem2Drop, 
        Prem3Item, 
        Prem3Qty, 
        Prem3Drop, 
        Prem4Item, 
        Prem4Qty,  
        Prem4Drop, 
        Prem5Item, 
        Prem5Qty, 
        Prem5Drop, 
        Prem10ItemPkging, 
        AckLtr1TypeCode, 
        AckLtr10ItemPkging, 
        ContactID,
        'N' [Continued]
FROM    [TU FAR Before VB]
UNION ALL 
SELECT   Campaign, 
        Prem6Item, 
        Prem6Qty, 
        Prem6Drop, 
        Prem7Item, 
        Prem7Qty, 
        Prem7Drop, 
        Prem8Item, 
        Prem8Qty, 
        Prem8Drop, 
        Prem9Item, 
        Prem9Qty, 
        Prem9Drop, 
        NULL, 
        NULL, 
        NULL, 
        Prem10ItemPkging, 
        NULL, 
        AckLtr10ItemPkging, 
        ContactID,
        'Y' [Continued]
FROM    [TU FAR Before VB]
WHERE   NOT
        (       Prem6Item IS NULL
            AND Prem7Item IS NULL
            AND Prem8Item IS NULL
            AND Prem9Item IS NULL
        );