【问题标题】:DB2 SQL Count over Union of multiple tables with different DatatypeDB2 SQL Count over Union of multiple tables with different Datatype
【发布时间】:2019-09-06 04:36:12
【问题描述】:

我想合并多个表,其中一些想计数。

Select A.CustomerId
      , A.CustomerGroup
      , ‘’        as count
From Customer A
Union 
Select  B.CustomerId
      , B.CustomerGroup
      , select(count(*) from Product C
                   Where C.productId = B.productId) as count
From Product B

出现集合运算符的操作数的第 3 列不兼容的问题。

【问题讨论】:

  • 请显示最少的样本数据和预期的结果集。
  • cobol 还活着吗? :)
  • 是的,大规模的。
  • @Jen。 . .样本数据和期望的结果真的很有帮助。

标签: mysql sql db2 cobol


【解决方案1】:

尝试如下,对于联合,您需要相同的数据类型

Select A.CustomerId
      , A.CustomerGroup
      , 0   as count
From Customer A
Union 
Select  B.CustomerId
      , B.CustomerGroup
      , select(count(*) from Product C
                   Where C.productId = B.productId
      ) as count
From Product B

【讨论】:

    【解决方案2】:

    如果您希望联合的第三列是数字(例如整数),那么参与联合的 所有 查询将需要具有该类型。此外,您可能应该重写第二个查询以使用左连接而不是相关子查询:

    SELECT
        A.CustomerId,
        A.CustomerGroup
        0 AS count
    FROM Customer A
    UNION ALL
    SELECT
        B.CustomerId,
        B.CustomerGroup,
        COUNT(C.productid)
    FROM Product B
    LEFT JOIN Product C
        ON C.productId = B.productId
    GROUP BY
        B.CustomerId,
        B.CustomerGroup;
    

    注意:我假设您在这里真的想要UNION ALL。如果您的逻辑是给定的客户 ID 和组实际上只能属于 CustomerProduct 表,则继续使用 UNION

    【讨论】:

      【解决方案3】:

      你可以试试这个。由于从您的查询来看,您的column 3 似乎需要空白空间。

      Select A.CustomerId
            , A.CustomerGroup
            , Cast(NULL as INT)  as count
      From Customer A
      Union All
      Select DISTINCT B.CustomerId
            , B.CustomerGroup
            , count(*) as count
      From Product B INNER JOIN 
      Product C Where C.productId = B.productId
      

      【讨论】:

      • 这不是最佳解决方案。
      【解决方案4】:

      我不确定这会完全返回您的结果,但它似乎更有用:

      SELECT C.CustomerId, C.CustomerGroup,
             COUNT(p.productid)
      FROM Customer C LEFT JOIN
           Product P
           ON C.CustomerId = P.CustomerId AND
              C.CustomerGroup = P.CustomerGroup
      GROUP BY C.CustomerId, C.CustomerGroup;
      

      我怀疑CustomerProduct 都有CustomerIdCustomerGroup 列。

      我怀疑您的原始查询可能是错误的,您可能真的打算这样做:

      SELECT C.CustomerId, C.CustomerGroup,
             COUNT(p.productid)
      FROM Customer C LEFT JOIN
           Product P
           ON C.ProductId = P.ProductId 
      GROUP BY C.CustomerId, C.CustomerGroup;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-24
        • 2022-12-01
        • 2016-01-14
        • 2022-12-01
        • 2022-12-02
        • 2021-09-08
        • 2011-01-20
        • 1970-01-01
        相关资源
        最近更新 更多