我的表格包含id
和两个产品列product
和product_other
。 product
列可能包含有效的产品名称,单词“other”或空白,因为它来自源。如果product_other
是“其他”,则product
将具有有效的产品名称,否则可能是空白的或随机包含有效的产品名称。
我需要将所有有效的产品名称拉到一个列中,并排除空白和“其他”条目。到目前为止,我尝试了两种方法,UNION
方法如下:
SELECT DISTINCT * FROM
(
SELECT id
, COALESCE(NULLIF(NULLIF(product, 'other'), ''), 'UNKNOWN') AS product
FROM myTable
UNION
SELECT id
, COALESCE(NULLIF(product_other, ''), 'UNKNOWN') AS product
FROM myTable
) k
ORDER BY id
这会产生所有行,包括product
的'UNKNOWN'值和同一product_other
的{{1}}的有效产品名称,当它只提供有效名称时
我使用的另一种方法是下面的id
方法:
CASE WHEN
但是,这个列表只生成了有效SELECT id
, CASE COALESCE(NULLIF(product, ''), 'UNKNOWN')
WHEN 'other' THEN COALESCE(NULLIF(product_other, ''), 'UNKNOWN')
ELSE COALESCE(NULLIF(product_other, ''), 'UNKNOWN')
END AS product
FROM myTable
ORDER BY id
列表(如果可用)或product
product_other
为“其他”或空白。它排除了存在有效product
产品和 product_other 值的情况的可能性。
另一种看待它的方法是,如果product
查询为k SELECT id, count(*) FROM (
,则在第一种情况下会有数量为2的行,无论是否为“UNKNOWN”,以及第二行每) GROUP BY id
只有一行。
所以,id
看起来像这样:
myTable
我希望查询结果如下所示:
id product product_other
------ --------- ---------------
155535 OTC COM
155536 OTC
155537 other COM
155538
感谢。
答案 0 :(得分:0)
试试这个:
CREATE TABLE #temp (id int , product varchar(10), product_other VARCHAR(10))
INSERT INTO #temp
VALUES(155535,'OTC','COM'),
(155536, '' ,'OTC'),
(155537,'other','COM'),
(155538,'','')
SELECT id
, CASE WHEN COALESCE(NULLIF(product, ''),NULLIF(product_other, '')) = 'other' AND NULLIF(product_other, '') IS NOT NULL THEN product_other
WHEN COALESCE(NULLIF(product, ''),NULLIF(product_other, '')) IS NULL AND NULLIF(product_other, '') IS NULL THEN 'UNKNOWN'
ELSE COALESCE(NULLIF(product, ''),NULLIF(product_other, '')) END AS product
FROM #temp
UNION
SELECT id
,CASE WHEN COALESCE(NULLIF(product_other, ''),NULLIF(product, '')) = 'other' AND NULLIF(product, '') IS NOT NULL THEN product_other
WHEN COALESCE(NULLIF(product_other, ''),NULLIF(product, '')) IS NULL AND NULLIF(product, '') IS NULL THEN 'UNKNOWN'
ELSE COALESCE(NULLIF(product_other, ''),NULLIF(product, '')) END AS product
FROM #temp;
所以实质上这就是逻辑:
SELECT id
, CASE WHEN COALESCE(NULLIF(product, ''),NULLIF(product_other, '')) = 'other' AND NULLIF(product_other, '') IS NOT NULL THEN product_other
WHEN COALESCE(NULLIF(product, ''),NULLIF(product_other, '')) IS NULL AND NULLIF(product_other, '') IS NULL THEN 'UNKNOWN'
ELSE COALESCE(NULLIF(product, ''),NULLIF(product_other, '')) END AS product
FROM myTable
UNION
SELECT id
,CASE WHEN COALESCE(NULLIF(product_other, ''),NULLIF(product, '')) = 'other' AND NULLIF(product, '') IS NOT NULL THEN product_other
WHEN COALESCE(NULLIF(product_other, ''),NULLIF(product, '')) IS NULL AND NULLIF(product, '') IS NULL THEN 'UNKNOWN'
ELSE COALESCE(NULLIF(product_other, ''),NULLIF(product, '')) END AS product
FROM myTable;
答案 1 :(得分:0)
SELECT *
FROM myTable
UNPIVOT(product_name FOR product_type IN (product, product_other)) u
WHERE
u.product_name NOT IN ('', 'other');