我有一个表,其中有数千行描述某个产品。它有关于产品特性的多个专栏。例如。
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的enum:
[Flags]
public enum ProductFeature : short
{
None = 0,
isOnSale = 0x001,
HasVeteranDiscount = 0x002,
IsTaxExempt = 0x004,
isGeneric = 0x008,
CanBeSoldSeperate = 0x010,
}
对于统计分析,我需要将上述数据从三个表中插入到一个表中,作为所有适用产品特性的按位或整数,以及属于该类别的产品计数以及产品销售计数,例如:
ProductTrend
ProductFeatures ItemsSold MonthSold
例如,如果一个产品销售,有一个或多个部分是通用的,有一个或多个部分可以单独销售,那么它是25。另一个产品有veterandiscount,并且有一个或多个部件可以单独出售,然后它的18 [hasveterandiscount | canbesoldseparate = 18]我的表应该是这样的:
ProductTrend
ProductFeatures ItemsSold MonthSold
25 34 April
18 12 May
这里我需要帮助的最重要的部分是如何将来自多个表中的多个列的产品数据组合成一个整数列productFeatures,并进行位操作。
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
试试这个,这里的例子
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