我是SQL的新手,我在分析某些数据方面有些挣扎。我有一个表[01-Jan-UserDefined],它是具有20MM行的风力数据集。 我创建了一个表[WINDDIR],该表将生成一个包含相关统计数据的汇总表,并根据风速和风向对数据行进行计数。
代码按列(风速)拆分计数,但不能按风向拆分。
有关如何解决此问题的任何提示?谢谢
UPDATE WINDDIR
SET [0WS1] = counter1,
[1WS2] = counter2,
[2WS3] = counter3,
FROM (SELECT COUNT(CASE WHEN [01-Jan-UserDefined].[WindRel m s ] <=1 then 1 else null end) AS counter1,
COUNT(CASE WHEN [01-Jan-UserDefined].[WindRel m s ] >1 AND [01-Jan-UserDefined].[WindRel m s ] <= 2 then 1 else null end) AS >counter2,
COUNT(CASE WHEN [01-Jan-UserDefined].[WindRel m s ] >2 AND [01-Jan-UserDefined].[WindRel m s ] <= 3 then 1 else null end) AS counter3,
from [01-Jan-UserDefined]) h
数据样本:
SET DATEFORMAT DMY
DECLARE @Table AS TABLE ([UTC] DATETIME
, [WindDirRel deg] INT
, [WindRel m s] DECIMAL(18, 2)
, [WINDDIR SECTOR] NVARCHAR(3)
, [WINDDIR SECTOR NO] INT);
INSERT INTO @Table
( UTC
, [WindDirRel deg]
, [WindRel m s]
, [WINDDIR SECTOR]
, [WINDDIR SECTOR NO])
VALUES ('27/01/2018 08:09', 127, 3.96, 'ESE', 6)
, ('27/01/2018 08:09', 125, 4.06, 'ESE', 6)
, ('27/01/2018 08:09', 125, 4.06, 'ESE', 6)
, ('13/01/2018 22:01', 13, 10.39, 'N ', 1)
, ('13/01/2018 22:01', 12, 10.13, 'N ', 1)
, ('13/01/2018 22:01', 12, 10.44, 'N ', 1);
SELECT * FROM @table
实际输出:
WINDDIR SECTOR 0WS1 1WS2 2WS3 3W4 4W5 5W6 6W7 7W8 8W9 9W10 10W
N 0 0 0 1 2 0 0 0 0 0 3
NNE 0 0 0 1 2 0 0 0 0 0 3
NE 0 0 0 1 2 0 0 0 0 0 3
ENE 0 0 0 1 2 0 0 0 0 0 3
ESE 0 0 0 1 2 0 0 0 0 0 3
所需的输出:
WINDDIR SECTOR 0WS1 1WS2 2WS3 3W4 4W5 5W6 6W7 7W8 8W9 9W10 10W
N 0 0 0 0 0 0 0 0 0 0 3
NNE 0 0 0 0 0 0 0 0 0 0 0
NE 0 0 0 0 0 0 0 0 0 0 0
ENE 0 0 0 0 0 0 0 0 0 0 0
ESE 0 0 0 1 2 0 0 0 0 0 0
答案 0 :(得分:0)
看看这个。还要注意我如何添加示例数据集-这将有助于其他人将来为您提供帮助。
DECLARE @Table AS TABLE (WINDIR NVARCHAR(3), [WindRel m s ] DECIMAL(18, 2));
INSERT INTO @Table (WINDIR, [WindRel m s ])
VALUES (N'N', 0.1)
, (N'N', 1.5)
, (N'N', 1.75)
, (N'N', 2.5)
, (N'NNE', 1.5)
, (N'NNE', 2.5);
SELECT WINDIR,COUNT(CASE WHEN [WindRel m s ]<=1 THEN 1 ELSE NULL END) AS [<1]
,COUNT(CASE WHEN [WindRel m s ]>1 AND [WindRel m s ] <= 2 THEN 1 ELSE NULL END) AS [1-2]
,COUNT(CASE WHEN [WindRel m s ]>2 THEN 1 ELSE NULL END) AS [>2]
FROM @Table GROUP BY WINDIR
答案 1 :(得分:0)
DECLARE @Table AS TABLE (WINDIR NVARCHAR(3), [WindRel m s ] DECIMAL(18, 2));
DECLARE @WINDIR AS TABLE (WINDIR NVARCHAR(3), [0WS1] INT, [1WS2] INT, [2WS3] INT);
INSERT INTO @WINDIR (WINDIR, [0WS1], [1WS2], [2WS3])
VALUES (N'N', 0, 0, 0)
, (N'NNE', 0, 0, 0);
INSERT INTO @Table (WINDIR, [WindRel m s ])
VALUES (N'N', 0.1)
, (N'N', 1.5)
, (N'N', 1.75)
, (N'N', 2.5)
, (N'NNE', 1.5)
, (N'NNE', 2.5);
WITH cte AS
(SELECT WINDIR
, COUNT(CASE WHEN [WindRel m s ] <= 1 THEN 1 ELSE NULL END) AS [0WS1]
, COUNT(CASE WHEN [WindRel m s ] > 1 AND [WindRel m s ] <= 2 THEN 1 ELSE NULL END) AS [1WS2]
, COUNT(CASE WHEN [WindRel m s ] > 2 THEN 1 ELSE NULL END) AS [2WS3]
FROM @Table
GROUP BY WINDIR)
UPDATE W
SET [0WS1] = cte.[0WS1]
, [1WS2] = cte.[1WS2]
, [2WS3] = cte.[2WS3]
FROM @WINDIR W
JOIN cte ON W.WINDIR = cte.WINDIR;
SELECT *
FROM @WINDIR;