我試圖將CASE
語句中的值組合在SQL Server
中。當這些值是正值時,它工作正常。當這些值是負值時,它會爆炸。在SQL Server CASE中對負值進行分組
Here's a link to the SQL Fiddle I created to replicate it:
下面是代碼:
-- 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+ - 不打破低valueranges。
任何人都可以看到我做錯了什麼?
「爆炸」和「不起作用」是什麼意思?您的第二個查詢明確排除了「WHERE」條款中的負數。 – Pondlife 2012-07-12 22:45:10
你是對的 - 更新查詢。即使這樣,我也沒有得到我期待的結果。 – mikebmassey 2012-07-12 22:46:20