2012-10-16 106 views
-1

我有一个T-SQL查询,我需要从总的CASE语句计数。T-SQL CASE(SQL Server 2000中)

我尝试添加一个UNION但我得到一个错误:

All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists.

任何想法?谢谢。

查询:

SELECT 
    CustomerID, Name, DueDate, 
    CASE WHEN DATEDIFF(Month, PaymentDate, DueDate) >= 1 
      THEN PaymentAmount ELSE 0 
    END AS [Early], 
    CASE WHEN DATEDIFF(Month, PaymentDate, DueDate) >=0 
      THEN PaymentAmount ELSE 0 
    END AS [On Time], 
    CASE WHEN DATEDIFF(Month, PaymentDate, DueDate) = -1 
      THEN PaymentAmount ELSE 0 
    END AS [Late] 
FROM 
    Customers 
WHERE 
    DATEDIFF(MONTH, PaymentDate,DueDate), GetDate()) = 1 
    AND PaymentAmount= DuesAmount 

UNION 

SELECT 
    '-Total', '', CustomerID, Name, DueDate, 
    SUM(CASE WHEN DATEDIFF(Month, PaymentDate, DueDate) >= 1 
       THEN PaymentAmount ELSE 0 END) AS [Early], 
    SUM(CASE WHEN DATEDIFF(Month, PaymentDate, DueDate) >= 0 
       THEN PaymentAmount ELSE 0 END) AS [On Time], 
    SUM(CASE WHEN DATEDIFF(Month, PaymentDate, DueDate) = -1 
       THEN PaymentAmount ELSE 0 END) AS [Late] 
FROM 
    Customers 
WHERE 
    DATEDIFF(MONTH, PaymentDate,DueDate), GetDate()) = 1 
    AND PaymentAmount = DuesAmount 
+0

@ruakh我完全同意你的评论。我们只能投票:) –

回答

3

错误说,“在包含UNION操作SQL语句的所有查询必须在其目标列表中的表达式的数量相等。”这意味着每个SELECT必须返回相同数量的表达式。

在你给我们的代码示例中,第一SELECT语句返回6个表达式,而第二个返回8:

SELECT CustomerID,    -- 1 
     Name,      -- 2 
     DueDate,     -- 3 
     CASE ... END AS [Early], -- 4 
     CASE ... END AS [On Time], -- 5 
     CASE ... END AS [Late]  -- 6 
... 
UNION 
SELECT '-Total',      -- 1 
     '',        -- 2 
     CustomerID,      -- 3 
     Name,       -- 4 
     DueDate,      -- 5 
     SUM(CASE ... END) AS [Early], -- 6 
     SUM(CASE ... END) AS [On Time], -- 7 
     SUM(CASE ... END) AS [Late]  -- 8 
... 

如何看第一SELECT回报6个表达式,但第二个返回8?在UNION中,所有SELECT语句都必须返回相同数量的表达式。

您可以在第一个查询返回NULL为没有在第二匹配,如果有必要列。例如:

SELECT NULL as [RowType],   -- 1 
     NULL as [Padding],   -- 2 
     CustomerID,    -- 3 
     Name,      -- 4 
     DueDate,     -- 5 
     CASE ... END AS [Early], -- 6 
     CASE ... END AS [On Time], -- 7 
     CASE ... END AS [Late]  -- 8 
... 
UNION 
SELECT '-Total',      -- 1 
     '',        -- 2 
     CustomerID,      -- 3 
     Name,       -- 4 
     DueDate,      -- 5 
     SUM(CASE ... END) AS [Early], -- 6 
     SUM(CASE ... END) AS [On Time], -- 7 
     SUM(CASE ... END) AS [Late]  -- 8 
... 

另请注意,您在DueDate列后没有逗号。

+0

保罗感谢您的信息。我现在能够无误地运行查询。但是我的结果中没有看到总数。有任何想法吗? – steve

+0

不,但您可能需要一个'ORDER BY ColumnName'来确保总数在最后。如果你想要客户总数,可以使用“GROUP BY CustomerID”。你可以试试'UNION ALL'来确保总数不会被重复丢弃。 –

+0

再次感谢。我确实找到了它在结果中间显示的总数。你是对的,我不得不添加一个ORDER BY。我有其他人协助我。以下是我必须对查询进行的调整以使其正常工作,再次感谢。 选择* '' (选择 '' 为[的ColumnName] )数据 ORDER BY CASE WHEN [客户] = '总计' THEN 1 ELSE [客户] END – steve