如果该组中的任何值为0,我想扫描一个表并将组内的值重新分配给0。我似乎无法通过搜索{{1}的各种组合来找出解决方案。 },Group By
和Partition
。
我开始的数据看起来像
Any
我希望结果显示为(包括换行符以便于解释)
CREATE TABLE #QP
(
[Method] VARCHAR(1),
[Station] VARCHAR(1),
[Instrument] VARCHAR(20),
[LastAnalysis] DATE,
[DaysPassed] INT
)
INSERT INTO #QP
(Method, Station, Instrument, LastAnalysis, DaysPassed)
VALUES
('A', 1, 'Polaris', '2016-07-19', 21),
('B', 1, 'Polaris', '2016-08-04', 5),
('C', 1, 'Polaris', '2016-07-31', 9),
('A', 2, 'Polaris', '2016-07-31', 9),
('B', 2, 'Polaris', '2016-08-09', 0),
('C', 2, 'Polaris', '2016-07-23', 17),
('A', 3, 'Polaris', '2016-08-09', 0),
('B', 3, 'Polaris', '2016-07-27', 13),
('C', 3, 'Polaris', '2016-07-19', 21)
我到目前为止最接近的是使用
Method Station Instrument LastAnalysis DaysPassed Weight
A 1 Polaris 2016-07-19 21 21
B 1 Polaris 2016-08-04 5 5
C 1 Polaris 2016-07-31 9 6
A 2 Polaris 2016-07-31 9 0
B 2 Polaris 2016-08-09 0 0
C 2 Polaris 2016-07-23 17 0
A 3 Polaris 2016-08-09 0 0
B 3 Polaris 2016-07-27 13 0
C 3 Polaris 2016-07-19 21 0
但是,当SELECT *,
CASE WHEN 0 = ANY(SELECT DaysPassed FROM #QP) THEN 0 ELSE DaysPassed END AS [Weight]
FROM #QP
WHERE Instrument = 'Polaris'
ORDER BY Station, Method
组中的值保持原样时,这会将Weight
列中的每个值设置为0。
如果这已有答案,我很想知道用于查找答案的正确搜索字词。
答案 0 :(得分:3)
我认为使用min()
窗口功能会起作用。试一试:
SELECT *,
case when min(DaysPassed) over (partition by station) = 0 then 0 else DaysPassed end as [Weight]
FROM #QP
WHERE Instrument = 'Polaris'
ORDER BY Station, Method
答案 1 :(得分:1)
java.time.YearMonth
返回
SELECT *
,Weight= Sign(min(DaysPassed) over (Partition By Station)) * DaysPassed
FROM #QP
WHERE Instrument = 'Polaris'
ORDER BY Station, Method