我有3张桌子a,b和c。 表a包含商店的ID,其收入日期和销售数量(机票)。
表b包含服装订单的ID,销售日期和计数。
表c包含id,日期和总计数。
SQL> select * from a;
STOREID EARNINGDATE COUNT_FLIGHT_TICKETS
-------------------- ----------- ----------------
store01 14980000 10
store01 14980001 32
store02 14980000 134
SQL> select * from b;
STOREID EARNINGDATE CLOTHES_SALE_COUNT
-------------------- ----------- ---------------
store01 14980000 6
store02 14980000 6
SQL> select * from c;
STOREID EARNINGDATE TOTAL_SALE_COUNT
-------------------- ----------- -------------
store01 14980001 32
store01 14980000 16
store02 14980000 134
鉴于上述表格,我必须打印所有商店ID,以及他们的总销售日期,航班销售和服装销售。
|StoreId | EarningDate | FlightCount | ClothingCount | TotalCount |
我使用了以下查询,但未能获得上述内容。
select b.storeId , sum(a.COUNT_FLIGHT_TICKETS),
sum(b.CLOTHES_SALE_COUNT), sum (c.TOTAL_SALE_COUNT)
from a
full outer join b on a.storeId = b.storeId
and a.EarningDate = b.earningdate
full outer join c on a.storeId = c.storeId
and a.earningDate = b.earningDate group by a.storeId;
此查询不会提供所有行并且有一些错误。
STOREID flight clothing total
------ --------- --------- --------------------
store02 134 6 134
store01 52 12 48
有人可以帮我纠正此查询以获得预期的输出吗?
答案 0 :(得分:4)
一种选择是获取thee表的UNION
然后按商店聚合:
SELECT
t.STOREID,
t.EARNINGDATE,
SUM(t.COUNT_FLIGHT_TICKETS) AS FlightCount,
SUM(t.CLOTHES_SALE_COUNT) AS ClothingCount,
SUM(t.TOTAL_SALE_COUNT) AS TotalCount
FROM
(
SELECT
STOREID,
EARNINGDATE,
COUNT_FLIGHT_TICKETS,
0 AS CLOTHES_SALE_COUNT,
0 AS TOTAL_SALE_COUNT
FROM a
UNION ALL
SELECT STOREID, EARNINGDATE, 0, CLOTHES_SALE_COUNT, 0
FROM b
UNION ALL
SELECT STOREID, EARNINGDATE, 0, 0, TOTAL_SALE_COUNT
FROM c
) t
GROUP BY
t.STOREID,
t.EARNINGDATE
这解决了您正确指出的连接问题,这可能需要完全外连接。 MySQL中的完全外部联接是一件麻烦事,无论如何通常不需要设计良好。
在这里演示:
答案 1 :(得分:3)
假设对于每个表,(storeId,earningdate)是唯一的或复合键,group by将是不必要的。 您可以尝试此查询。
select
IF(isnull(a.STOREID), IF(isnull(b.STOREID), c.STOREID, b.STOREID),a.STOREID) as StoreId,
IF(isnull(a.EARNINGDATE), IF(isnull(b.EARNINGDATE), c.EARNINGDATE, b.EARNINGDATE),a.EARNINGDATE) as EarningDate,
IF(isnull(COUNT_FLIGHT_TICKETS),0,COUNT_FLIGHT_TICKETS) as FlightCount,
IF(isnull(CLOTHES_SALE_COUNT),0,CLOTHES_SALE_COUNT) as ClothingCount,
IF(isnull(TOTAL_SALE_COUNT),0,TOTAL_SALE_COUNT) as TotalCount
from a full outer join b
on a.storeId = b.storeId and a.EarningDate = b.earningdate
full outer join c
on a.storeId = c.storeId and a.earningDate = c.earningDate;
结果是:
STOREID EarningDate flight clothing total
------ ------------- --------- --------- --------------------
store01 14980000 10 6 16
store02 14980000 134 6 134
store01 14980001 32 0 32
这是您的预期结果吗? 我想你忘记了收入日期。
鉴于上述表格,我必须打印所有商店ID 总销售,航班销售和服装销售的赚取日期。
| StoreId | EarningDate | FlightCount | ClothingCount | TotalCount |