好的,所以我有一个关于如何修复以下查询获取多行的问题。我期望将具有相同“持续时间”的所有行放入一行。我确定这是一个新手的错误,但我仍然是新手。谢谢你的帮助。
Select UPPERAGE,
case when [DurationLower] <= 2 THEN [DurationLower] ELSE NULL END AS 'First
trail year' ,
case when [DurationLower] >= 3 THEN [DurationLower] ELSE NULL END AS 'Next
trail year',
case when [DurationLower] <= 2 THEN Rate/100 ELSE NULL END AS 'First trail
%',
case when [DurationLower] >= 3 THEN Rate/100 ELSE NULL END AS 'Next trail %'
From Picasso.PageToProduct_VW pp
left join Picasso.PageToProductToRate_vw ppr on ppr.PageToProductID=
pp.PageToProductID
left join Picasso.ProductRates_VW r on ppr.ProductRatesID= r.ProductRatesID
wHERE pp.PageID = '7686A1'
and r.RateType = 'BASIS POINTS'
Group by upperage
我正在寻找的是第1行和第1行。 2组合和行3&amp; 4要结合
答案 0 :(得分:1)
我不确定当前查询是如何工作的(除非您使用的是mysql,但屏幕截图似乎是SQL Server)。
无论如何,你需要在CASE
表达式上使用聚合函数(我正在使用SUM
):
SELECT UPPERAGE,
SUM(CASE
WHEN [DurationLower] <= 2 THEN [DurationLower]
ELSE NULL
END) AS [First trail year],
SUM(CASE
WHEN [DurationLower] >= 3 THEN [DurationLower]
ELSE NULL
END) AS [Next trail year],
SUM(CASE
WHEN [DurationLower] <= 2 THEN Rate/100
ELSE NULL
END) AS [First trail %],
SUM(CASE
WHEN [DurationLower] >= 3 THEN Rate/100
ELSE NULL
END) AS [Next trail %]
FROM Picasso.PageToProduct_VW pp
LEFT JOIN Picasso.PageToProductToRate_vw ppr
ON ppr.PageToProductID = pp.PageToProductID
LEFT JOIN Picasso.ProductRates_VW r
ON ppr.ProductRatesID = r.ProductRatesID
WHERE pp.PageID = '7686A1'
AND r.RateType = 'BASIS POINTS'
GROUP BY upperage
;
答案 1 :(得分:0)
您似乎有多个看起来相同的UPPERAGE
值。如果它是数字,那可能是因为它们的差异很小。如果它是一个字符串,它可能就像尾随空格。
假设值为数字,您可以尝试:
Select floor(UPPERAGE) as upperAge,
max(case when [DurationLower] <= 2 THEN [DurationLower] END) AS First_
trail_year,
max(case when [DurationLower] >= 3 THEN [DurationLower] END) AS Next _trail_year,
max(case when [DurationLower] <= 2 THEN Rate/100 END) AS First_trail_%,
max(case when [DurationLower] >= 3 THEN Rate/100 END) AS Next_trail_percent
From Picasso.PageToProduct_VW pp left join
Picasso.PageToProductToRate_vw ppr
on ppr.PageToProductID = pp.PageToProductID left join
Picasso.ProductRates_VW r
on ppr.ProductRatesID= r.ProductRatesID
where pp.PageID = '7686A1' and r.RateType = 'BASIS POINTS'
Group by floor(UPPERAGE)
注意:
select
中有未分隔的列。rate / 100.0
。max()
作为运算符来组合事物。 sum()
也可能是合适的。