0

我有一个场景,我将在其中显示列值与特定行值的总和。我从小计中给出 A、B 和 C 类。如果小计hvs 80,我会给A,从81-90 B和91-100,设置为100

例如

Class   totalstudent     subtotal        category 
1        20                20             A
2        30                50             A
3        15                65             A
4        20                85             B
5        10                95             C
6         5                100            C

如何在上述情况下显示小计。需要在 SQL 中编写获取查询。

4

3 回答 3

0
USE CTE and get your desired result :


CREATE TABLE #Table(Class INT, totalstudent INT,category    
VARCHAR(10))

INSERT INTO #Table(Class , totalstudent ,category )
SELECT 1,20,'A' UNION ALL
SELECT 2,30,'A' UNION ALL
SELECT 3,15,'A' UNION ALL
SELECT 4,20,'B' UNION ALL
SELECT 5,10,'C' UNION ALL
SELECT 6,5,'C' 

;WITH CTE ( _Class , _totalstudent , _subtotal , _category) AS
(
   SELECT Class , totalstudent ,totalstudent ,category
   FROM #Table WHERE Class = 1
   UNION ALL
   SELECT Class , totalstudent , totalstudent + _subtotal  ,category
   FROM #Table
   JOIN CTE ON Class = _Class  + 1
)

SELECT * FROM CTE
于 2017-01-11T06:42:52.487 回答
0

您需要执行运行总操作

select * into #t from (select 1 Class ,20 totalstudent union all select 2,30 union all select 3,15 union all select 4,20 union all select 5,10 union all select 6,5) x

SELECT class,totalstudent,subtotal, CASE WHEN subtotal<=80 THEN 'A' WHEN subtotal between 81 and 90 THEN 'B' WHEN subtotal between 91 and 100 THEN 'C' END Category FROM (SELECT t2.class, t2.totalstudent, SUM(t1.totalstudent) 小计 FROM #t t1 JOIN #t t2 on t1.class <=t2.class GROUP by t2.class, t2.totalstudent
)x ORDER BY CLASS

于 2017-01-11T06:43:00.177 回答
0

检查这个。

        SELECT Class,totalstudent, 
        SUM(totalstudent)over(order by Class) as subtotal,
        Case When SUM(totalstudent)over(order by Class) <= 65 then 'A'  
        When SUM(totalstudent)over(order by Class) < 86 then 'B'  
        When SUM(totalstudent)over(order by Class) > 85 then 'C'  end As category  
        FROM #Table
        group by Class,totalstudent
        order by Class
于 2017-01-11T07:07:25.307 回答