分组和多个列数和总和

时间:2015-11-18 13:05:13

标签: sql ms-access count sum

我有一张列出学生成绩的表格,

AG          T1    T2     T3
L0011001    A     B       A          
L0011002    A     B       B          
L0011003    A     A       C          
L0011004    A     A       C          

我希望AG的输出像这样:

L0011001       2A 1B
L0011002       1A 2B
L0011003       2A 1C
L0011004       2A 1C

如何获得这个?

3 个答案:

答案 0 :(得分:3)

您的数据格式非常非常糟糕。每个" T"和每个学生。

但是,有时候我们会遇到糟糕的数据格式。您可以使用iif()

执行所需操作
select ag,
       (iif(t1 = 'A', 1, 0) + iif(t2 = 'A', 1, 0) + iif(t2 = 'A', 1, 0)) as A_s,
       (iif(t1 = 'B', 1, 0) + iif(t2 = 'B', 1, 0) + iif(t2 = 'B', 1, 0)) as B_s,
       (iif(t1 = 'C', 1, 0) + iif(t2 = 'C', 1, 0) + iif(t2 = 'C', 1, 0)) as C_s
from t;

这并不是你想要的。它将值放在不同的列中 - 这种格式对我来说更有意义。

针对您的具体格式:

select ag,
       (iif(A_s > 0, A_s & "A ") &
        iif(B_s > 0, B_s & "B ") &
        iif(C_s > 0, C_s & "C ")
       )
from (select ag,
             (iif(t1 = 'A', 1, 0) + iif(t2 = 'A', 1, 0) + iif(t2 = 'A', 1, 0)) as A_s,
             (iif(t1 = 'B', 1, 0) + iif(t2 = 'B', 1, 0) + iif(t2 = 'B', 1, 0)) as B_s,
             (iif(t1 = 'C', 1, 0) + iif(t2 = 'C', 1, 0) + iif(t2 = 'C', 1, 0)) as C_s
      from t
     ) as x

答案 1 :(得分:0)

您可能想要考虑联合查询和交叉表,输出并不完全符合您的意愿,但它确实有意义。

TRANSFORM Count(qry.ag) AS countofag
SELECT qry.ag
FROM   (SELECT tbl.ag,
               tbl.t1
        FROM   tbl
        UNION ALL
        SELECT tbl.ag,
               tbl.t2
        FROM   tbl
        UNION ALL
        SELECT tbl.ag,
               tbl.t3
        FROM   tbl) AS qry
GROUP  BY qry.ag
PIVOT qry.t1; 

答案 2 :(得分:0)

Just see if below query works for you.

`SELECT AG,ALL_VAL,
(LENGTH(ALL_VAL) - LENGTH(REPLACE(ALL_VAL, 'A', '')))  || 'A' || ' '||
(LENGTH(ALL_VAL) - LENGTH(REPLACE(ALL_VAL, 'B', '')))  || 'B' || ' '||
(LENGTH(ALL_VAL) - LENGTH(REPLACE(ALL_VAL, 'C', '')))  || 'C'  as OUTPUT
FROM ( 
SELECT AG,T1||T2||T3 AS ALL_VAL FROM t_s
) RSLT` 

I got the below output using above query.

 - L0011001-->ABA-->    2A 1B 0C
 - L0011002-->ABB-->    1A 2B 0C
 - L0011003-->AAC-->    2A 0B 1C
 - L0011004-->AAC-->    2A 0B 1C