我正在尝试在SQL Server中创建一个表变量,其中包含按季度分组的3列数据。我已成功为3列中的每一列选择适当的数据,但不知道如何使用每个附加查询更新表变量的内容。
因此,我不是拥有一个包含4行(每季度一个)和3列数据的表,而是在数据列中有12行(4个季度重复3次)和大量空值。
如何在没有NULLS的情况下创建表格的仅4行版本?
查询:
DECLARE @temp TABLE (oYear INT, oQuarter INT, chin FLOAT, press FLOAT, pull FLOAT)
DECLARE @sDate AS DATE, @eDate AS DATE, @athName AS VARCGAR(50),
@chin1RM AS FLOAT, @press1RM AS FLOAT, @pull1RM AS FLOAT;
SET @sDate = '2016-10-01';
SET @eDate = '2017-10-01';
SET @athName = 'Steve';
INSERT INTO @temp (oYear, oQuarter, chin)
SELECT
DATEPART(YEAR, Day.Date),
DATEPART(QUARTER, Day.Date),
MAX(Pred1RMBMF)
FROM
GymLoad
JOIN
Session ON Session.id = GymLoad.SessionID
JOIN
Day ON Day.id = Session.DayID
JOIN
Athlete ON Athlete.id = Day.AthleteID
WHERE
(ExerciseID = 200 OR ExerciseID = 198)
AND FullName = @athName
AND Day.Date >= @sDate
AND Day.Date <= @eDate
GROUP BY
DATEPART(YEAR,Day.Date), DATEPART(QUARTER,Day.Date);
INSERT INTO @temp (oYear, oQuarter, press)
SELECT
DATEPART(YEAR, Day.Date),
DATEPART(QUARTER, Day.Date),
MAX(Pred1RMBMF)
FROM
GymLoad
JOIN
Session ON Session.id = GymLoad.SessionID
JOIN
Day ON Day.id = Session.DayID
JOIN
Athlete ON Athlete.id = Day.AthleteID
WHERE
(ExerciseID = 164 OR ExerciseID = 174)
AND FullName = @athName
AND Day.Date >= @sDate
AND Day.Date <= @eDate
GROUP BY
DATEPART(YEAR, Day.Date), DATEPART(QUARTER, Day.Date);
INSERT INTO @temp (oYear, oQuarter, pull)
SELECT
DATEPART(YEAR, Day.Date),
DATEPART(QUARTER, Day.Date),
MAX(Pred1RMBMF)
FROM
GymLoad
JOIN
Session ON Session.id = GymLoad.SessionID
JOIN
Day ON Day.id = Session.DayID
JOIN
Athlete ON Athlete.id = Day.AthleteID
WHERE
(ExerciseID = 183 OR ExerciseID = 183)
AND FullName = @athName
AND Day.Date >= @sDate
AND Day.Date <= @eDate
GROUP BY
DATEPART(YEAR, Day.Date), DATEPART(QUARTER, Day.Date);
SELECT * FROM @Temp
查询当前返回的结果集:
oYear oQuarter chin press pull
------------------------------------------
2017 1 104.02 NULL NULL
2017 2 102.22 NULL NULL
2017 3 100.54 NULL NULL
2016 4 104.3 NULL NULL
2017 1 NULL 81.61 NULL
2017 2 NULL 71.26 NULL
2017 3 NULL 75.86 NULL
2016 4 NULL 80 NULL
2017 1 NULL NULL 91.95
2017 2 NULL NULL 68.97
2017 3 NULL NULL 73.75
2016 4 NULL NULL 85.33
非常感谢任何帮助。
答案 0 :(得分:2)
按年和季度汇总,并在数据列上使用汇总函数(例如MAX
)来删除空值。
SELECT
oYear,
oQuarter,
MAX(chin) AS chin,
MAX(press) AS press,
MAX(pull) AS pull
FROM @Table
GROUP BY
oYear,
oQuarter;