SQL如何不使用Union子句将单条记录拆分为两行查询结果
实现方案
不需要使用UNION/UNION ALL即可完成行拆分,以下是两种可直接落地的写法:
方案1:CROSS JOIN 配合表值构造器(跨数据库兼容性最好)
核心思路是通过VALUES子句直接构造包含两个目标税种的2行虚拟表,和原表做笛卡尔关联后,通过条件判断给对应字段赋值,非当前税种的金额字段置0即可。
整个语句不会出现UNION关键字,完全符合要求,支持SQL Server 2008+、MySQL 8.0+、PostgreSQL、SQLite 3.33+等绝大多数现代数据库。
完整可运行代码:
-- 测试数据准备 select taxtype,taxable,taxfree into #tb from (values('mixed',10,20)) tb(taxtype,taxable,taxfree) -- 核心查询逻辑 select v.taxtype, case when v.taxtype = 'taxable' then t.taxable else 0 end as taxable, case when v.taxtype = 'taxfree' then t.taxfree else 0 end as taxfree from #tb t cross join (values ('taxable'), ('taxfree') ) v(taxtype) drop table if exists #tb
方案2:UNPIVOT 列转行运算符(语法更简洁)
如果你的数据库支持UNPIVOT语法(SQL Server、Oracle、PostgreSQL 等均支持),可以直接用列转行运算符把taxable、taxfree两列拆分为两行,再补全对应字段值即可,代码更简洁,执行性能也更优。
核心查询代码:
select taxtype, case when taxtype = 'taxable' then amount else 0 end as taxable, case when taxtype = 'taxfree' then amount else 0 end as taxfree from #tb unpivot ( amount for taxtype in (taxable, taxfree) ) u
两种写法的执行结果完全符合预期:
| taxtype | taxable | taxfree |
|---|---|---|
| taxable | 10 | 0 |
| taxfree | 0 | 20 |
注:方案中使用的
VALUES是SQL标准的表值构造语法,不属于UNION子句范畴,完全满足不使用UNION的限制要求。
内容的提问来源于stack exchange,提问作者goshjosh
相关产品推荐
相关产品推荐

