简体   繁体   中英

DB2 SQL Count over Union of multiple tables with different Datatype

I want to union multiple tables and some of them want to count.

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

The problem occurred that column 3, of the operands of a set operator are not compatible.

try like below, for union you need same datatype

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

If you intend the third column of the union to be numeric (eg an integer), then all queries contributing to the union would need to have that type. In addition, you should probably rewrite the second query to use a left join rather than a correlated subquery:

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;

Note: I am assuming that you really want UNION ALL here. If instead your logic is that a given customer ID and group can really only belong to either the Customer or Product table, then continue using UNION .

You may try this. Since from your query it seems like you need blank space for your 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

I'm not sure this returns exactly the result that you have, but it seems more useful:

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;

I am suspicious that both Customer and Product have the columns CustomerId and CustomerGroup .

I suspect that your original query might be wrong and you might really intend:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM