如何 select 来自 SQL 中多列的数据子集?

How to select subset of data from multiple columns in SQL?

假设我有一个 table 如下,我想 select 购买超过 1 件商品的客户。

customer item1 item2 item3 item4
1 10 NULL NULL NULL
2 5 11 NULL NULL
3 7 NULL 9 NULL
4 NULL NULL 2 NULL
5 7 13 9 NULL

我的最终输出应该是这样的

customer item1 item2 item3 item4
2 5 11 NULL NULL
3 7 NULL 9 NULL
5 7 13 9 NULL

我的密码是

SELECT  
       customer
      ,item1
      ,item2
      ,item3
       item4
FROM StoreData
WHERE item1 IS NOT NULL OR 
      item2 IS NOT NULL OR
      item3 IS NOT NULL OR
      item4 IS NOT NULL

但这似乎不正确?有什么建议么?非常感谢

尝试这样的事情:

WHERE 
(
 (CASE WHEN item1 IS NOT NULL THEN 1 ELSE 0 END) 
+(CASE WHEN item2 IS NOT NULL THEN 1 ELSE 0 END) 
+(CASE WHEN item3 IS NOT NULL THEN 1 ELSE 0 END) 
+(CASE WHEN item4 IS NOT NULL THEN 1 ELSE 0 END) 
) > 1

你可以试试:

SELECT s.* 
from StoreData s 
inner join  (
               select customer,concat_ws('-',item1,item2,item3,item4) as orders
               from StoreData
             ) as t1 on t1.customer=s.customer
where CHARINDEX('-',orders ) >= 1;

Demo

这个问题的另一种方法是使用“UNPIVOT”表达式:

SELECT customer, COUNT(*) --, Item, Quantity
FROM dbo.StoreData
UNPIVOT  (
    Quantity FOR Item IN (item1, item2, item3, item4) 
) AS UnpivotTable
GROUP BY
    customer
HAVING
    COUNT(*) > 1

UNPIVOT 命令可帮助您将 item1、item2、...、itemN 视为单行。 然后你可以在上面应用一个基本的分组来检查计数是否大于所需的数量。