SQL计算基于字段类型和按类型分组

时间:2016-02-11 01:45:18

标签: sql calculated-field

数据库包括FamID,TicketType和Amt 我希望计算每个家庭每种票类的总金额,并根据所有票类的总数按家庭从高到低排序。

数据库值为:

FamID           TicketType             Amt
1                1                     10
1                1                     10
1                2                     20
1                3                     30
2                2                     20
2                1                     10
2                1                     10
2                1                     10
2                3                     30
3                3                     30
3                3                     30
3                3                     30

希望结果是

Family         Type 1         Type 2        Type 3         Total
3                0               0             90            90
2                30              20            30            80
1                20              20            30            70

我想做太多吗?

1 个答案:

答案 0 :(得分:2)

您从未指定过您的RDBMS,但是以下的数据透视查询应该可以在大多数主要数据库中使用而几乎没有修改:

SELECT t.`Type 1`, t.`Type 2`, t.`Type 3`,
    (t.`Type 1` + t.`Type 2` + 2*t.`Type 3`) AS Total
FROM
(
    SELECT FamID AS Family,
        SUM(CASE WHEN TicketType = 1 THEN Amt ELSE 0 END) AS `Type 1`,
        SUM(CASE WHEN TicketType = 2 THEN Amt ELSE 0 END) AS `Type 2`,
        SUM(CASE WHEN TicketType = 3 THEN Amt ELSE 0 END) AS `Type 3`,
    FROM Tickets
    GROUP BY FamID
) t
ORDER BY t.Total DESC