如何从查询结果中将一行中的单元格设为空白?
Posted
技术标签:
【中文标题】如何从查询结果中将一行中的单元格设为空白?【英文标题】:How to make a cell blank in a row from a query result? 【发布时间】:2016-11-03 23:07:21 【问题描述】:我有一个查询如下:
SELECT
cc.chain_desc as chain_desc
,cc.chain_id as chain_id
,COUNT(distinct t.trans_id) as TranCount
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
GROUP BY cc.chain_desc, cc.chain_id
UNION
SELECT
'TOTAL'
,0
,COUNT(distinct t.trans_id)
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
上面的查询在执行时会返回以下结果:
我需要将结果显示如下:
“Chain_Id”列是“整数”类型,我怎样才能将其设为空白?
【问题讨论】:
【参考方案1】:你可以简单地选择 null
.....
UNION
SELECT
'TOTAL'
, NULL::INTEGER
,COUNT(distinct t.trans_id)
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
LEFT OUTER JOIN chain_desc as cc
ON l.chain_id = cc.chain_id
WHERE
t.loc_country = 'U'
AND c.issuer_id IN (156966,166203)
AND t.trans_date >= '2016-10-01 00:00'
and t.trans_date < '2016-10-31 00:00'
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
因为 null 不是您可以尝试在第一个查询上方添加的类型
DEFINE test INT;
LET test = NULL;
......
SELECT
'TOTAL'
, test
,COUNT(distinct t.trans_id)
.....
或者像@Jonathan Leffler 建议的那样使用NULL::INTEGER
或CAST(NULL AS INTEGER)
【讨论】:
如果我选择 NULL,我会得到一个错误。我正在使用 SQL Workbench 来测试查询。 我已经更新了 asnwer .. 希望清晰有用 @Newbee:在 Informix 中,您需要指定 null 的类型——例如NULL::INTEGER
— 而不是只使用普通的 NULL
,它可以是任何类型。如果您愿意,也可以使用CAST(NULL AS INTEGER)
。【参考方案2】:
在 Informix 中,您可以在投影列表中使用 NULL
,但列必须具有类型。由于在 Informix 中 NULL
没有类型,因此您需要使用 CAST
。
SELECT NULL::INTEGER AS id FROM systables WHERE tabid = 1;
SELECT CAST(NULL AS INTEGER) AS id FROM systables WHERE tabid = 1;
您可以查看其他问题的答案 (Informix: Select null problem)。
您可以查看 IBM 知识中心 (NULL Keyword)。
【讨论】:
【参考方案3】:一种方法是转换为NULL
:
(case when cc.chain_id <> 0 then cc.chain_id end) as chain_id
另一个是将所有内容都转换为字符串:
(case when cc.chain_id <> 0 then cast(cc.chain_id as varchar(255)) else '' end) as chain_id
【讨论】:
以上是关于如何从查询结果中将一行中的单元格设为空白?的主要内容,如果未能解决你的问题,请参考以下文章