【问题标题】:Convert multiple columns to a single integer with bitwise operation in SQL在 SQL 中使用按位运算将多列转换为单个整数
【发布时间】:2013-04-28 09:22:26
【问题描述】:

我有数千行描述某些产品的表格。它有多个关于产品功能的专栏。例如

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   

我有一个描述产品功能的枚举:

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

为了进行统计分析,我需要将三个表中的上述数据作为所有适用产品功能的按位或整数插入到一个表中,其中包含属于该类别的产品数量以及产品销售数量,例如:

ProductTrend
ProductFeatures ItemsSold MonthSold

例如,如果一个产品是非销售的并且有一个或多个部分是通用的并且有一个或多个部分可以单独出售,那么它的 25。 而另一种产品有退伍军人折扣,并且有一个或多个零件可以单独出售,那么它的 18 [HasVeteranDiscount | CanBeSoldSeperate = 18] 我的表格应该是这样的:

ProductTrend
ProductFeatures ItemsSold MonthSold
25              34        April
18              12        May

我需要帮助的最重要的部分是如何将来自多个表中的多个列的有关产品的数据合并到一个具有按位运算的整数列 productFeatures 中。

【问题讨论】:

  • 感谢 Andomar 和 1010101(您的名字本身是如此面向位,您应该知道这一点 :))为按位解决方案和 SQL 小提琴。我曾经使用 regextester 进行正则表达式和其他用于 html 和 xml 在线编辑的东西,现在我了解了 SQL fiddle。这个解决方案非常适合我。

标签: sql sql-server


【解决方案1】:

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.

【讨论】:

    【解决方案2】:

    试试这个,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 2012-12-15
      • 2019-06-11
      • 2012-07-03
      • 2023-03-21
      • 1970-01-01
      • 2017-04-25
      相关资源
      最近更新 更多