我正在尝试CASE
将SQL Server
. 当值为正时,它工作正常。当值为负时,它会爆炸。
这是代码:
-- Create the table --
CREATE TABLE Test (
ClientID varchar(12),
Value decimal(12,10)
PRIMARY KEY (ClientID)
);
-- Load the data --
INSERT INTO Test (ClientId, Value)
VALUES('1','10'),
('2','-10'),
('3','11.2'),
('4','-11.6'),
('5','12.544'),
('6','-13.456'),
('7','14.04928'),
('8','-15.6089'),
('9','15.7351'),
('10','-18.1063'),
('11','17.6234'),
('12','-21.0034'),
('13','19.7382'),
('14','-24.3639'),
('15','22.1068'),
('16','-28.2621'),
('17','24.7596'),
('18','-32.7841'),
('19','27.7307'),
('20','-38.0296'),
('21','31.0584'),
('22','-44.1141'),
('23','34.785499'),
('24','-51.1726'),
('25','38.9597'),
('26','-59.3602'),
('27','43.6349'),
('28','-68.8579'),
('29','48.8711'),
('30','-79.8751');
现在运行CASE
语句:
SELECT
CASE
WHEN Value BETWEEN 0 AND 20 THEN '0-20'
WHEN Value BETWEEN 21 AND 40 THEN '20-40'
ELSE '40+'
END as ValueRange, count(*) as count
FROM Test
WHERE Value > 0
GROUP BY CASE
WHEN Value BETWEEN 0 AND 20 THEN '0-20'
WHEN Value BETWEEN 21 AND 40 THEN '20-40'
ELSE '40+'
END
;
这很好用。结果:
VALUERANGE count
0-20 7
20-40 6
40+ 2
现在有负值 - 它不起作用:
SELECT
CASE
WHEN Value BETWEEN 0 AND -20 THEN '0-20'
WHEN Value BETWEEN -21 AND -40 THEN '20-40'
ELSE '40+'
END
as ValueRange, count(*) as count
FROM Test
WHERE Value < 0
GROUP BY CASE
WHEN Value BETWEEN 0 AND -20 THEN '0-20'
WHEN Value BETWEEN -21 AND -40 THEN '20-40'
ELSE '40+'
END
;
结果:
VALUERANGE count
40+ 15
它将所有内容分组为 40+ - 没有分解较低的值范围。
谁能看到我做错了什么?