我现在已经在这个问题上遇到了一段时间,并且没有取得任何进展。我甚至不知道是否可能......
我有一张桌子:
+------+------------+-------+---------+------------+
| Item | Date | RUnit | FDHUnit | Difference |
+------+------------+-------+---------+------------+
| A | 19/04/2016 | 21000 | 20000 | 1000 |
| B | 20/04/2016 | 2500 | 500 | 2000 |
+------+------------+-------+---------+------------+
是否可以在同一个表格中为每个items
创建一个新行,这些行将显示Difference
以及其他一些列?
我想要的输出是这样的:
+------+------------+-------+---------+------------+
| Item | Date | RUnit | FDHUnit | Difference |
+------+------------+-------+---------+------------+
| A | 19/04/2016 | 21000 | 20000 | |
| A | 19/04/2016 | NULL | NULL | 1000 |
| B | 20/04/2016 | 2500 | 500 | |
| B | 20/04/2016 | NULL | NULL | 2000 |
+------+------------+-------+---------+------------+
原因是我希望显示一个新列,并指出它是Held directly
或not held directly
。
答案 0 :(得分:0)
是的,请使用union all
:
select item, date, ruunit, fdhunit, difference
from t
union all
select item, date, null, null, runit - fdhunit
from t
order by item, (case when runit is not null then 1 else 2 end);
order by
将结果按照结果显示的顺序排列。没有order by
,记录的顺序是不确定的。
答案 1 :(得分:0)
试试这种方式
select * from
(select item, date, ruunit, fdhunit, '' as difference
from t
union all
select item, date, null as ruunit, null as fdhunit, difference
from t) a
order by item, date
答案 2 :(得分:0)
试试这个
插入表格:
insert into table1
select item,date,null,null,(Runit-fdhunit) from table1 where (Runit-fdhunit)
正常结果: 从table1中选择* 联合所有 从table1中选择item,date,null,null,(Runit-fdhunit)其中(Runit-fdhunit)<> 0
答案 3 :(得分:0)
试试这个。将cast(null as number)
替换为difference
列的实际类型
select item, date, r.ruunit, r.fdhunit, r.difference
from t
cross apply (
select n=1, ruunit, fdhunit, cast(null as number) difference
UNION
select n=2, null, null, difference ) r
order by item, date, n