更改字段条件语句

时间:2018-10-23 10:31:31

标签: sql-server tsql if-statement

我有一张桌子,像这样:

>Date--Country--Courier--Division--Volume
>
>datetime--varchar--varchar--varchar--varchar--int
>
>datetime--varchar--varchar--varchar--varchar--int

所有这些数据都收集在一个临时表中,代表一个月的数据。

最后的范围是将总体积小于某个值的国家更改为“其他”。

例如:

>Country -- Volume
>
>Germany -- 1200
>
>Albania -- 250

我想将其更改为:

>Country -- Volume
> 
>Germany -- 1200
>
>Other -- 250

我一直在尝试基于

SUM(Volume) OVER(PARTITION BY Country) < x

但是看起来我距离实现这一目标还很遥远。

不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:1)

从逻辑的角度来看,您可以按照以下方式进行操作:

DECLARE @threshold int = 250;
SELECT
   0 AS Priority, 
   Country, 
   Volume
   FROM YourTable
   WHERE Volume >= @threshold
UNION ALL
SELECT 
   1 AS Priority, 
   'Others' AS Country,
   SUM(Volume) AS Volume
FROM YourTable
WHERE Volume < @threshold
ORDER BY Priority

鉴于您的数据可能是:

Country - Volume
----------------
Germany - 1000
Italy   - 500
France  - 300
Albania - 120
Spain   - 100
Sweden  - 90

您会得到:

Country - Volume
----------------
Germany - 1000
Italy   - 500
France  - 300
Others  - 310 -- equals to sum of countries under @threshold value