如何编写SQL查询以获得我想要的输出?

时间:2017-11-08 08:07:22

标签: mysql sql

示例数据:

表:类别

+--------+--------+
| parent |  name  |
+--------+--------+
| fruit  | apple  |
| fruit  | banana |
| fruit  | grapes |
| fruit  | apple  |
| cars   | duster |
| cars   | swift  |
| games  | nfs    |
+--------+--------+

我需要实现这样的目标:

+-------+--------+---+
| fruit | apple  | 2 |
|       | banana | 1 |
|       | grapes | 1 |
| cars  | duster | 1 |
|       | swift  | 1 |
| games | nfs    | 1 |
+-------+--------+---+

即。以这种方式计数和分组

3 个答案:

答案 0 :(得分:1)

使用Sql Server(T-SQL)的方法

DECLARE @Categories TABLE(

    CategoryName    VARCHAR(MAX),
    Item            VARCHAR(MAX)
)

/*Add data to the tempory table for demo purpose*/
INSERT INTO @Categories( CategoryName, Item )
VALUES  ( 'fruit', 'apple' ),
        ( 'fruit', 'banana' ),
        ( 'fruit', 'grapes' ),
        ( 'fruit', 'apple' ),
        ( 'cars', 'duster' ),
        ( 'cars', 'swift' ),
        ( 'games', 'nfs' );

/*Query to get the result*/
SELECT  CASE WHEN ROW_NUMBER() OVER(PARTITION BY CategoryName ORDER BY Item) = 1 
             THEN CategoryName ELSE '' END AS 'Category Caption', 
             Item, COUNT(Item)  AS 'Count'
FROM @Categories
GROUP BY CategoryName, Item
ORDER BY CategoryName 

答案 1 :(得分:0)

SELECT COLUMN1 , COLUMN2 , SUM(COLUMN3 ) AS QTY
FROM CATEGORY
GROUP BY COLUMN1 , COLUMN2
ORDER BY COLUMN1 , COLUMN2

答案 2 :(得分:0)

构建表并插入记录:

CREATE TABLE category (element_type char(20), element_name char(20));
INSERT INTO  category VALUES ('fruit', 'apple');
INSERT INTO  category VALUES ('fruit', 'banana');
INSERT INTO  category VALUES ('fruit', 'grapes');
INSERT INTO  category VALUES ('fruit', 'apple');
INSERT INTO  category VALUES ('cars', 'duster');
INSERT INTO  category VALUES ('cars', 'swift');
INSERT INTO  category VALUES ('games', 'nfs');

制定查询:

   SELECT element_type AS Type,
          element_name AS Name,
          count(element_name) AS Count
     FROM category
 GROUP BY element_type, element_name;

结果:

Type    Name    Count
cars    duster  1
cars    swift   1
fruit   apple   2
fruit   banana  1
fruit   grapes  1
games   nfs     1