Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 删除行值并转换为单列值_Sql_Sql Server_Stored Procedures - Fatal编程技术网

Sql 删除行值并转换为单列值

Sql 删除行值并转换为单列值,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我有一个存储过程返回一个如下所示的表: ID | Type | Price | Description ------------------------------- 7 | J | 50.00 | Job 7 | F | 20.00 | Freight 7 | P | 30.00 | Postage 7 | H | 5.00 | Handling ID | Type | Price | Description | FreightPrice ---------

我有一个存储过程返回一个如下所示的表:

ID | Type | Price | Description
-------------------------------
7  | J    | 50.00 | Job
7  | F    | 20.00 | Freight
7  | P    | 30.00 | Postage
7  | H    |  5.00 | Handling
ID | Type | Price | Description | FreightPrice
-----------------------------------------
7  | J    | 50.00 | Job         | 20.00
7  | P    | 30.00 | Postage     | 20.00
7  | H    |  5.00 | Handling    | 20.00
我希望它像这样返回表:

ID | Type | Price | Description
-------------------------------
7  | J    | 50.00 | Job
7  | F    | 20.00 | Freight
7  | P    | 30.00 | Postage
7  | H    |  5.00 | Handling
ID | Type | Price | Description | FreightPrice
-----------------------------------------
7  | J    | 50.00 | Job         | 20.00
7  | P    | 30.00 | Postage     | 20.00
7  | H    |  5.00 | Handling    | 20.00
是否有一种方法可以使用以下查询:

SELECT * FROM Temp WHERE Type = 'F'
但是将“运费”行作为列返回,而只返回“价格”值


从我所看到的情况来看,我可能需要使用PIVOT操作符来实现这一点,但这似乎过于复杂。是否有一种方法可以使用CASE或IF表达式实现此结果?

根据您提供的数据,有一行具有描述值:运费。假设是这种情况,请尝试:

select ID,Type,Price,Description,
       FreightPrice = (select Price 
                       from mytable 
                       where Description = 'Freight')
from mytable
where Description <> 'Freight'
如果货运行始终向右移动,则可以硬编码此逻辑,假设它始终是单行,如中所示:

select
  id,
  type,
  price,
  description,
  (select price from t where description = 'Freight') as freightprice
from t
where description <> 'Freight'

注意:如果您的表中包含多行运费,此查询将崩溃。

感谢您验证我的答案:是的,我们得到了相同的答案:我不知道您可以执行FreightPrice=。。。在SQL Server中。反正+1@TheImpaler有几种方法可以在sql server中编写别名。亚伦·伯特兰在观察他们方面做得很好。这就成功了,我显然想得太多了。谢谢你,艾瑞和穿刺者。“我会接受这个答案,因为它是第一个。”SeanLange很好的文章。