[英]All from table A and include a row for each of a set from table B even if there is no related record in Table B
I had a hard job describing this simple problem...我很难描述这个简单的问题......
I want to return a series of data points for a stacked bar chart for each stack Label and Bar, whether or not there is a record for the Label/Bar datapoint, a null value being returned where there is no data record.我想为每个堆栈 Label 和 Bar 的堆积条形图返回一系列数据点,无论是否有标签/条形数据点的记录,在没有数据记录的情况下返回 null 值。 The 'missing' Label must also be included:
还必须包括“缺失”的 Label:
Label Bar Value a X 99 a Y 23 a Z 97 b X null b Y 32 b Z null
I have table DataLabel that contains the Labels for the each type of datapoint in the bar stack and a table DataSeries that contains the X-axis Labels and the Y-axis values to be calculated for each datapoint.我有一个表 DataLabel,其中包含条形堆栈中每种类型数据点的标签,还有一个表 DataSeries,其中包含要为每个数据点计算的 X 轴标签和 Y 轴值。
create table DataLabel (id number , label varchar2(10)); Insert into DataLabel values (1, 'a'); Insert into DataLabel values (2, 'b'); Create table DataSeries (id number , DataLabel_id number , val number , DataSeriesName varchar2(5)); Insert into DataSeries values (1, 1, 99, 'X'); Insert into DataSeries values (11, 1, 23, 'Y'); Insert into DataSeries values (12, 2, 32, 'Y'); Insert into DataSeries values (21, 1, 97, 'Z');
The problem arises, where the DataSeries table be does not contain a corresponding value for a DataLabel for a given datapoint.问题出现了,其中 DataSeries 表不包含给定数据点的 DataLabel 的相应值。
I have managed an inelegant solution that does return the desired result in SQLfiddle using a Union join, but is there a better solution....?我已经管理了一个不优雅的解决方案,它使用联合连接在SQLfiddle中返回了所需的结果,但是有更好的解决方案......?
Use a cross join
to generate the rows and then a left join
to bring in the values:使用
cross join
来生成行,然后使用left join
来引入值:
select dl.label, dsn.dataseriesname,
ds.val
from datalabel dl cross join
(select distinct dataseriesname from dataseries
) dsn left join
dataseries ds
on ds.datalabel_id = dl.id and
ds.dataseriesname = dsn.dataseriesname
order by dl.label, dsn.dataseriesname;
A cross join
among tables containing a correlated subquery might be an option:包含相关子查询的表之间的
cross join
可能是一种选择:
select distinct label, DataSeriesName as bar,
(select val
from DataSeries
where DataSeriesName=s.DataSeriesName
and DataLabel_id=l.id) as value
from DataSeries s
cross join DataLabel l
order by label, bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.