计算分配给不同类型的值的频率

时间:2012-10-26 04:52:07

标签: sql-server tsql sql-server-2005 count

我提前为我糟糕的描述道歉,我想不出更好地说出来的方法,但我会尽力解释它。

假设我以这种方式设置了表格:

输入表

Itm Type
A   Apple
B   Orange
C   Apple
B   Grape
D   Peaches
B   Apple
C   Grapes
E   Apple
A   Apple

目标是生成一个表格,显示每个项目(A,B,C,D和E)以及分配给该项目的每种类型的总数。

目标输出表

Itm    Apple  Orange  Grape  Peaches    
A       2       0       0       0   
B       1       1       1       0
C       1       0       1       0
D       0       0       0       1
E       1       0       0       0

我正在使用的查询现在显示一个表格,其中似乎总结了所有项目的所有类型并将该值放在每一行上。

提前致谢!

3 个答案:

答案 0 :(得分:1)

SELECT 
    Item, 
    ISNULL([Apple], 0) 'Apple', 
    ISNULL([Orange], 0) 'Orange', 
    ISNULL([Grapes], 0) 'Grapes', 
    ISNULL([Peaches], 0) 'Peaches'
FROM
(
    SELECT 
        Item, Type, count(*) 'ItemTypeCount'
    FROM 
        ItemTypes
    GROUP BY Item, Type
) AS T
PIVOT
(
    SUM(ItemTypeCount) FOR Type IN ([Apple], [Orange], [Grapes], [Peaches])
) As PivotResults

答案 1 :(得分:1)

查询:

select Itm, Apple, Orange, Grape, Peaches
from items
pivot(count(Type) for Type in (Apple, Orange, Grape, Peaches)) p

示例架构和数据。在StackOverflow上发布问题时,您应始终提供这些内容。

create table items(Itm char(1), Type varchar(10));
insert items select
'A',   'Apple' union all select
'B',   'Orange' union all select
'C',   'Apple' union all select
'B',   'Grape' union all select
'D',   'Peaches' union all select
'B',   'Apple' union all select
'C',   'Grapes' union all select
'E',   'Apple' union all select
'A',   'Apple';

结果:

| ITM | APPLE | ORANGE | GRAPE | PEACHES |
------------------------------------------
|   A |     2 |      0 |     0 |       0 |
|   B |     1 |      1 |     1 |       0 |
|   C |     1 |      0 |     0 |       0 |
|   D |     0 |      0 |     0 |       1 |
|   E |     1 |      0 |     0 |       0 |

SQL Fiddle

答案 2 :(得分:0)

尝试运行此

SELECT 
         ITEM 
         , SUM(APPLE) AS APPLE 
         , SUM(Grapes) AS Grapes
         ,SUM(Orange) AS Orange 
         , SUM(Peaches) AS Peaches
FROM(SELECT 
        ITEM 
        ,CASE WHEN TYPE = 'APPLE' THEN  COUNT(*) ELSE 0 END AS APPLE
        ,CASE WHEN TYPE = 'Grapes' THEN  COUNT(*) ELSE 0 END AS  Grapes
        ,CASE WHEN TYPE = 'Orange' THEN  COUNT(*) ELSE 0 END AS Orange
        ,CASE WHEN TYPE = 'Peaches' THEN  COUNT(*) ELSE 0 END AS Peaches 
    FROM ITEM
    GROUP BY ITEM , TYPE 
    ) AS A GROUP BY ITEM