sql在表上执行左连接

oknrviil  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(275)

我有两个表,第一个表(表1)包含id,dat\u beg,period,dat\u end。第二个表(表2)包含多个列,包括cod\u client和cod\u contract。我想对上面提到的表执行左连接。请问有人知道我的代码有什么问题吗?
先谢谢你,

select id, DATE_TRUNC('day', table1.dat_beg) as date, s1, cod_client, sum(perid) as sum_period from (
select id, table1.dat_end, x, table1.dat_beg , 
(case when TRIM(x) like 'cat/%' then 'cat'
when TRIM(x) like 'fol/%' then 'follower'
else 'unknown'
end) as s1,
(extract(epoch from (table1.dat_end - table1.dat_beg)))/60 as sum_period
from table1 left join table2 on table1.id = table2.cod_contract
where table1.dat_end < '2262-04-11' and table1.dat_beg >= '2019-01-10'
) X
group by table1.id, table1.s1, table1.date
mzmfm0qo

mzmfm0qo1#

这个查询实际上有很多问题。我要发布我认为可能有用的东西,然后是我不确定的东西。

SELECT 
    x.id, 
    DATE_TRUNC('day', x.dat_beg) AS date_day, 
    x.s1, 
    x.cod_client, 
    SUM(x.sum_period) AS sum_period 
FROM 
    (
        SELECT 
            id, 
            table1.dat_beg, 
            table2.cod_client,
            CASE 
                WHEN TRIM(x) LIKE 'cat/%' THEN 'cat'
                WHEN TRIM(x) LIKE 'fol/%' THEN 'follower'
                ELSE 'unknown'
            END AS s1,
            (EXTRACT(epoch FROM (table1.dat_end - table1.dat_beg)))/60 AS sum_period
        FROM 
            table1 
            LEFT JOIN table2 ON table1.id = table2.cod_contract
        WHERE 
            table1.dat_end < '2262-04-11' 
            AND table1.dat_beg >= '2019-01-10'
    ) x
GROUP BY 
    x.id, 
    DATE_TRUNC('day', x.dat_beg), 
    x.s1, 
    x.cod_client

问题:
codu客户端没有包含在子查询中,所以我猜它来自 table2 ?
你引用了 table1 在子查询之外,它没有任何意义。我把这个改成了 x 相反;
你有很多额外的(不必要的(真的!)括号;
你的表中有列 x 外部查询中未使用的子查询;
你在给一个叫做 perid ,但这在任何地方都不存在,我猜这是命中注定的 sum_period ?
编辑
小提琴演示

7gcisfzg

7gcisfzg2#

除了group by子句和sum函数-

SELECT id, 
       Date_trunc('day', table1.dat_beg) AS date, 
       s1, 
       cod_client, 
       Sum(sum_period)                        AS perid 
FROM   (SELECT id, 
               table1.dat_end, 
               x, 
               table1.dat_beg, 
               ( CASE 
                   WHEN Trim(x) LIKE 'cat/%' THEN 'cat' 
                   WHEN Trim(x) LIKE 'fol/%' THEN 'follower' 
                   ELSE 'unknown' 
                 END ) 
               AS s1, 
               ( Extract(epoch FROM ( table1.dat_end - table1.dat_beg )) ) / 60 
               AS 
                      sum_period 
        FROM   table1 
               LEFT JOIN table2 
                      ON table1.id = table2.cod_contract 
        WHERE  table1.dat_end < '2262-04-11' 
               AND table1.dat_beg >= '2019-01-10') X 
GROUP  BY id, 
       Date_trunc('day', table1.dat_beg), 
       s1, 
       cod_client

相关问题