我需要一些关于sql-joins的帮助。 我有3个select语句,它给我一个这样的输出:
select-statement A:
location amount_A
7234 17
7456 2
select-statement B:
location number_x
7234 4455
7456 555
select-statement C:
location errors
7234 1
7456 44537
我希望将结果放在一个表中,如下所示:
location Amount_A number_x errors
7234 17 4455 1
7456 2 555 44537
实现这一目标的最佳和/或最简单的方法是什么?每个select语句都使用其他表。?!
这些是陈述:
A: select substring(column_a for 4) location, count(*) Amount_A from table_a where column_a like '7%' group by location ;
B: select substring(e.column_xy for 4), count(*) number_x from table_b b, table_e e , table_c c where b.stationextension_id = e.id and b.id = c.id and ( c.column_h in ( 'value_a', 'value_b' ) ) group by substring(e.column_xy for 4) ;
C: select substring(name from 1 for 4), count(*) from errors group by substring(name from 1 for 4) ;
答案 0 :(得分:1)
使用Inner Join
连接所有三个查询。
还使用Inner Join语法连接两个表,这些表比旧式逗号分隔连接更具可读性。
Substring
函数有一些不同的参数希望那些是原始查询中的例子,你需要将适当的值传递给substring函数
select a.location,Amount_A ,number_x,errors from
(
SELECT substring(column_a for 4) location, count(*) Amount_A FROM table_a WHERE column_a LIKE '7%' GROUP BY location
) A
inner join
(
SELECT substring(e.column_xy for 4) location , count(*) number_x FROM table_b b inner join table_e e on b.stationextension_id = e.id and b.stationextension_id = e.id
inner join table_c c on b.id = c.id
where c.column_h IN ( 'value_a', 'value_b' ) ) GROUP BY substring(e.column_xy FOR 4) ;
) B on a.location = b.location
inner join
(
SELECT substring(name from 1 FOR 4) location, count(*) errors FROM errors GROUP BY substring(name FROM 1 FOR 4) ;
)
C on c.location = b.location
答案 1 :(得分:0)
您可以将所有三个查询合并为一个
identical(coef(m1), coef(m2))
## [1] TRUE
identical(vcov(m1), vcov(m2))
## [1] TRUE
答案 2 :(得分:0)
试试这个:
select
a.location, a.amount_A,
b.number_x,
c.errors
from (
select_satement_A
) as a
join (
select_satement_B
) as b on a.location = b.location
join (
select_satement_C
) as c on a.location = c.location
如果select_satement_A
的所有数据都需要retrieved
使用left join
。
将使用select_satement_A
和select_satement_B
中的相应数据检索select_satement_C
中的所有数据。如果找不到与join
条件匹配的null
将被替换。
select
a.location, a.amount_A,
b.number_x,
c.errors
from (
select_satement_A
) as a
left join (
select_satement_B
) as b on a.location = b.location
left join (
select_satement_C
) as c on a.location = c.location
对于要检索的所有数据,请使用full join
。
答案 3 :(得分:0)
您总是可以将一些语句与一些左外连接组合在一起。我认为地点可能没有任何错误。
如果没有更好地理解基础数据,以正确的顺序获取连接有点棘手,但我希望这能指向正确的方向。
select substring(e.column_xy for 4) location,
count(a.column_xy) Amount_A,
count(e.ie) number_x,
count(e2.name) errors
from table_b b
inner join table_e e on b.stationextension_id = e.id
inner join table_c c on b.id = c.id
left join table_a a on substring(e.column_xy for 4) = substring(a.column_a from 1 for 4)
and a.column_a like '7%'
left join errors e2 on substring(e.column_xy for 4) = substring(e2.name from 1 for 4)
where c.column_h in ( 'value_a', 'value_b' )
group by substring(e.column_xy for 4);