(SQL)根据值将一个表的列分为两列

时间:2020-03-10 17:17:56

标签: sql sql-server

我们所拥有的:

Property    Cost
Car 2       0k
Bike        10k
House       500k
Condo       250k
Mobile-Home 90k

所需:

Property    Cost    Value
Car         11-20k  N/A
Bike         0-10k  N/A
House        N/A    251-500k
Condo        N/A    100-250k
Mobile-home  N/A    21-90k

我在表格中有一栏代表“属性”,一栏代表“成本”。我想为“成本”创建一个单独的列,将别名指定为“值”,并取决于显示为“属性”的内容,这对我的“成本”列也同样适用。

我还需要两个列的全部范围

I.e 0-10k, 11-20k, 21-100k, 101-250k and 251-500k

我将如何编写此查询?使用MSSS。

4 个答案:

答案 0 :(得分:2)

这回答了问题的原始版本。

如果我的理解正确,那么您需要case表达式:

select property,
       (case when property in ('car', 'bike') then cost end) as cost,
       (case when property not in ('car', 'bike') then cost end) as value
from t;

答案 1 :(得分:0)

我将创建一个表“ Properties”,其列为auto inc int ID,varchar(something)名称,IsCost位不为空。

然后:

SELECT Name,
  (CASE WHEN IsCost=1 THEN COST END) AS cost, 
  (CASE WHEN IsCost=0 THEN COST END) as value
FROM YourTable yt
JOIN Properties p
  ON yt.property = p.Name

如果您怀疑这可能会更进一步(Cost / Value本质上不是布尔值),那么您可能想要添加IsValue列,或创建一个指向另一个引用propertyType的表的列(Cost / Value,价值,费用等)。

答案 2 :(得分:0)

您可以使用滞后条件获取下一个成本的值:

;with tableA as
(select 'Car' as Property,'20K' as Cost union
select 'Bike','10K' union
select 'House','500K' union
select 'Condo','250K' union
select 'Mobile-Home','90K')

select a.Property,
       case when property in ('car', 'bike') 
                 then ISNULL(LAG(Cost) Over (Order by CAST(Replace(a.Cost,'K','') as int)),'0K') + ' - ' + Cost
            else 'N/A'
            end as cost,
       case when property not in ('car', 'bike') 
                 then ISNULL(LAG(Cost) Over (Order by CAST(Replace(a.Cost,'K','') as int)),'0K') + ' - ' + Cost
            else 'N/A'
            end as value
from tableA a

我也用'N / A'代替了NULL。希望这会有所帮助。

答案 3 :(得分:0)

我将在两个表上执行简单的连接

不清楚您如何在成本和价值之间切换以获得最终结果

示例

Declare @Table1 Table ([Property] varchar(50),[Cost] varchar(50))  Insert Into @Table1 Values 
 ('Car','20k')
,('Bike','10k')
,('House','500k')
,('Condo','250k')
,('Mobile-Home','90k')

Declare @Table2 Table ([Title] varchar(50),[R1] varchar(50),[R2] varchar(50))  Insert Into @Table2 Values 
 ('0-10k',0,10)
,('11-20k',11,20)
,('21-100k',21,100)
,('101-250k',101,250)
,('251-500k',251,500)

Select A.Property
      ,Cost  = IsNull(B.Title ,'N/A')
      ,Value = IsNull(C.Title ,'N/A')
 From @Table1 A
 Cross Apply (values (try_convert(money,replace(Cost,'K',''))) )V(amt)
 Left Join @Table2 B on amt between B.R1 and B.R2 and amt<=20
 Left Join @Table2 C on amt between C.R1 and C.R2 and amt> 20

返回

Property    Cost    Value
Car         11-20k  N/A
Bike        0-10k   N/A
House       N/A     251-500k
Condo       N/A     101-250k
Mobile-Home N/A     21-100k