我有一个带有客户ID的表,然后是30+列,带有0或1.我想在第一列中返回客户ID,然后在第二列中返回客户ID的名称列<> 0。 表的内容如下:
CustomerID, Product1, product2, product3, ...
123456 0 1 1
我想要回归:
123456, Product2
123456. Product3
...
我目前使用的代码......
答案 0 :(得分:0)
听起来您需要重新设计数据库以更好地满足您的要求。
鉴于目前的情况应该能够做到以下几点:
SELECT CustomerID,'Product1' FROM yourtable WHERE product1<>0
UNION
SELECT CustomerID,'Product2' FROM yourtable WHERE product2<>0
UNION
SELECT CustomerID,'Product3' FROM yourtable WHERE product3<>0
等等。
答案 1 :(得分:0)
你必须把桌子弄掉,这将是丑陋的,但可以简单地通过使用足够数量的工会来完成,就像这样;
SELECT CustomerId, 'Product1' as product FROM mytable WHERE product1 != 0
UNION ALL
SELECT CustomerId, 'Product2' as product FROM mytable WHERE product2 != 0
UNION ALL
SELECT CustomerId, 'Product3' as product FROM mytable WHERE product3 != 0
UNION ALL
....
UNION ALL
SELECT CustomerId, 'Product31' as product FROM mytable WHERE product31 != 0
UNION ALL
SELECT CustomerId, 'Product32' as product FROM mytable WHERE product32 != 0;