我的表格如下:
Ride_distance Ride_type
100 A
50 B
25 B
25 C
10 C
40 A
... ...
现在我希望将每种类型的所有距离都计算出来并显示如下:
Tot_Type_A Tot_Type_B Tot_Type_C
140 75 35
我该怎么做?
答案 0 :(得分:3)
SELECT SUM(Ride_distance), Ride_type
FROM your_table
GROUP BY Ride_type
答案 1 :(得分:2)
从分组开始:
SELECT SUM(Ride_distance),Ride_type FROM rides GROUP BY Ride_type
如果您必须将它们放在同一行,请使用pivot:
SELECT 'TotalRide' as Total_Ride_Length, [A], [B], [C]
FROM
(SELECT Ride_distance, Ride_type FROM rides) AS SourceTable
PIVOT (
SUM(Ride_distance) FOR Ride_type IN ([A], [B], [C])
) AS PivotTable;
答案 2 :(得分:2)
是的,有可能,但你必须为每种类型写一个case
语句:
select
sum(case ride_type when 'A' then ride_distance else 0 end) as tot_type_A,
sum(case ride_type when 'B' then ride_distance else 0 end) as tot_type_B,
sum(case ride_type when 'C' then ride_distance else 0 end) as tot_type_C
from your_table
答案 3 :(得分:0)
使用PIVOT
;
select
A as Tot_Type_A,
B as Tot_Type_B,
C as Tot_Type_C
from
dbo.the_table
pivot (
sum(Ride_distance) for Ride_type in ([A],[B],[C])
) pvt