2013-04-28 62 views
1

我有一張表,其中有數千行描述了某些產品。它有多個關於產品功能的專欄。對於例如在SQL中按位操作將多列轉換爲單個整數

productid productname isOnSale HasVeteranDiscount IsTaxExempt Otherdata1 Otherdata2 ... 
1   rice  0     1  1   info1  info2 
2   camera  1  0     0   info3  info4 

另一個表

[Productparts] 
Partid parentproductid isGeneric CanBeSoldSeperate OtherData1 Otherdata2 ... 

另一個表:

ProductId ItemsSold Datesold 
1   23  4/20/2013 

我有一個描述productfeature枚舉:

[Flags] 
public enum ProductFeature : short 
{ 
    None = 0, 
    isOnSale = 0x001, 
    HasVeteranDiscount = 0x002, 
    IsTaxExempt = 0x004, 
    isGeneric = 0x008, 
    CanBeSoldSeperate = 0x010, 
} 

進行統計分析我需要插入上述數據來自三t ABLES到一個表中,作爲按位或運算有與產品銷售計數,如屬於這一類沿產品的計數的所有適用的產品功能整數

ProductTrend 
ProductFeatures ItemsSold MonthSold 

對於例如,如果一個產品isonsale並具有一個或多個部分是通用的,並且有一個或多個部分可以單獨銷售,然後是它的25. 而另一種產品已經有一個或多個部分可以單獨銷售,那麼它的18個[HasVeteranDiscount | CanBeSoldSeperate = 18] 我的表應該是這樣的:

ProductTrend 
ProductFeatures ItemsSold MonthSold 
25    34  April 
18    12  May 

這裏最重要的部分,我需要幫助的是我怎麼約在多個表的多個列的產品的數據合併成一個單一的整數列產品屬性按位操作。

+0

感謝Andomar和1010101(你的名字本身就是這樣面向比特的你有啥可知道這:))爲按位解決方案和SQL小提琴。我曾經使用regextester爲正則表達式和其他的東西在網上的HTML和XML編輯,現在我瞭解了關於SQL小提琴。這個解決方案對我來說非常合適 – 2013-04-28 16:01:41

回答

3

SQL Server進行按位支持|或:

select productid 
,  productname 
,  case when isOnSale = 1 then 1 else 0 end | 
     case when HasVeteranDiscount = 1 then 2 else 0 end | 
     case when IsTaxExempt = 1 then 4 else 0 end as Flags 
from Table1 

Example on SQL Fiddle.

1

試試這個,sample here

select productid,intheMonthOf,features,sum(itemsold) as TotalSoldItems 
    from (

    select a.productid,Datename(month,datesold) as intheMonthOf, itemsold, 

    case when a.isonsale =1 then 1 else 0 end | 
    case when a.hasveterrandiscount =1 then 2 else 0 end | 
    case when a.istaxexempt =1 then 4 else 0 end | 
    case when b.isgeneric =1 then 8 else 0 end | 
    case when b.canbesoldseparate =1 then 10 else 0 end as features 

    from t1 a 
    left outer join t2 b on a.productid=b.parentproductid 
    inner join t3 c on c.porductid=a.productid)main 
    group by productid,intheMonthOf,features 
相關問題