如何根据同一表中第二列中的值拆分1列数据?

时间:2017-06-12 19:41:36

标签: sql sql-server

我的数据库中有一列看起来像这样; L表示已加载,E表示空白:

Loaded/Empty

与“里程数”相同的表中的列:

Mileage

我试图找到一种方法让它分开,并将所有里程的总和加上()加载并清空成2列,即总加载里程和总空里程?

这样的事情: Total

我已经尝试了一个案例,自我加入,可能还有一个支点或观点,我无法弄清楚如何得到我想要的东西。

3 个答案:

答案 0 :(得分:1)

您可以尝试IF(actually IIF in SQL Server):

COALESCE(SUM(IF(loaded = 'L', move_distance, 0)),0) AS when_loaded,
COALESCE(SUM(IF(loaded = 'E', move_distance, 0)),0) AS when_empty

当表为空(或任何其他WHERE不产生匹配)时,COALESCE允许病态情况,并且SUM将返回NULL。

CASE

COALESCE(SUM(CASE WHEN loaded = 'L' THEN move_distance ELSE 0 END), 0)

答案 1 :(得分:0)

最简单的经验是将此查询创建为union:

Select Loaded, move_distance Move_Loaded, 0 Move_Empty
from mytable
where Loaded = 'L'
UNION
Select Loaded, 0 , move_distance
from mytable
where Loaded = 'E'

如果您只想使用总和:

Select Loaded, sum(move_distance) Move_Loaded, 0 Move_Empty
from mytable
where Loaded = 'L'
group by Loaded, 0
UNION
Select Loaded, 0 , sum(move_distance)
from mytable
where Loaded = 'E'
group by Loaded, 0

您可以按行忽略组中的“0”。

答案 2 :(得分:0)

普通sql的简便方法如下。

SELECT 
SUM(CASE WHEN loaded = 'L' THEN move_distance ELSE 0 END) as 
LoadedMoveDistance
SUM(CASE WHEN loaded = 'E' THEN move_distance ELSE 0 END) as 
LoadedMoveDistance
FROM tablename

其他方式是使用Pivot,这是SQL服务器特定的,它将如下所示。

select [L] as Move_distance_loaded, [E] as Move_distance_empty
from
(
Select loaded, move_distance from table
) tb
PIVOT
(
SUM(move_distance)
FOR loaded IN ([L], [E])
) As pvt

你需要尝试使用pivot,上面的代码将无法正常提供。