首页 > 解决方案 > 如何使用 SQL 查询在不同的行中打印结果?

问题描述

我正在执行下面的 SQL 查询,其结果显示为一行,但我不想将其打印为一行,而是要拆分为两个不同的行并打印该值。

SQL查询:

select
(case when max(PK_MTF1000) = min(PK_MTF1000) and count(PK_MTF1000) = count(*) or max(PK_MTF1000) is null then 'same' else 'diff'end)as PK_MTF1000,max(PK_MTF1000),min(PK_MTF1000) + CHAR(13) ,
(case when max(MID) = min(MID) and count(MID) = count(*) or max(MID) is null then 'same' else 'diff'end) as MID,max(MID),min(MID)
from MTF1000 where ORG=' BULGER CAPITAL LLC';

输出:

same    NULL  NULL diff 1962008204906400    1962008204823K00

期望输出分成两个不同的行并打印输出如下

same    NULL  NULL

diff    1962008204906400    1962008204823K00

尝试使用 CHAR(13)

select
(case when max(PK_MTF1000) = min(PK_MTF1000) and count(PK_MTF1000) = count(*) or max(PK_MTF1000) is null then 'same' else 'diff'end)as PK_MTF1000,max(PK_MTF1000),min(PK_MTF1000) + CHAR(13) +  --<--,
(case when max(MID) = min(MID) and count(MID) = count(*) or max(MID) is null then 'same' else 'diff'end) as MID,max(MID),min(MID)
from MTF1000 where ORG=' BULGER CAPITAL LLC';

得到错误为:

-ORA-00936:缺少表达式
00936。00000 -“缺少表达式”
*原因:
*操作:
行错误:2 列:189

有没有办法分成两行?

标签: sqloracleoracle11g

解决方案


我想你可能想要一个 UNION,所以每组数据都有自己的行。

select
    (case when max(PK_MTF1000) = min(PK_MTF1000) and count(PK_MTF1000) = count(*) or max(PK_MTF1000) is null then 'same' else 'diff'end)as PK_MTF1000, 
    max(PK_MTF1000), 
    min(PK_MTF1000)
from MTF1000 where ORG=' BULGER CAPITAL LLC'
union all
select
    (case when max(MID) = min(MID) and count(MID) = count(*) or max(MID) is null then 'same' else 'diff'end) as MID, 
    max(MID), 
    min(MID)
from MTF1000 where ORG=' BULGER CAPITAL LLC';

推荐阅读