-2

我有一个包含类别和子类别字段的表。我想要特定类别下不同子类别的总和。喜欢表

Category  | Sub category | Amount 
----------+--------------+--------
Children  |  Cloth       |  200
Children  |  Cloth       |  500
Transport |  Fuel        |  300
Children  |  School      |  500

我想要儿童类别下的布料总和。就像不同的类别一样。请帮忙。

4

3 回答 3

3

从您的问题中不清楚您到底想要什么,但我认为它是以下之一:

如果您想要每个类别的每个子类别,请执行以下操作:

select
    category,
    sub_category,
    sum(amount) as total
from mytable
group by category, sub_category

如果您想要“儿童”的子类别,请执行以下操作:

select
    sub_category,
    sum(amount) as total
from mytable
group by sub_category
where category = 'Children'
于 2013-07-13T03:44:04.797 回答
2

像这样?

SELECT
     sub_category
    ,sum(amount)
FROM
    the_table
GROUP BY
    sub_category
WHERE
    category = 'Children';

或者

SELECT
     category
    ,sub_category
    ,sum(amount)
FROM
    the_table
GROUP BY
     category
    ,sub_category


使用 SQLite 测试/演示:

$ sqlite3 test.sqlite
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table t ( category varchar, subcategory varchar, amount int);
sqlite> insert into t values ('children', 'cloth', 200), ('children', 'cloth', 500), ('transport', 'fuel', 300), ('children', 'school', 500);
sqlite> select * from t ;
children|cloth|200
children|cloth|500
transport|fuel|300
children|school|500
sqlite> 
sqlite> select category, subcategory, sum(amount) from t group by category, subcategory;
children|cloth|700
children|school|500
transport|fuel|300
sqlite> 
于 2013-07-13T03:16:58.923 回答
1
select
    category,
    sub_category,
    sum(amount) as total
from mytable where sub_category = 'Cloth'
group by category, sub_category
于 2013-07-13T04:28:11.567 回答