簡體   English   中英

在MySQL中,如何計算一列中某個值范圍的出現次數,而不是另一列中所有唯一值的出現次數?

[英]How can I count the number of occurrences of a range of values in one column, against all unique values in another, in MySQL?

我的品牌表中有任意數量的重復項,尺寸列中的選項數量有限:

Item    Brand           Size
1       BiGNRG          AA
2       LongLife        AAA
3       LongLife        AAA
4       BiGNRG          AA
5       LongLife        D
6       EcoBatt         C
7       BiGNRG          AAA
8       BiGNRG          AA
9       EcoBatt         C

我需要一個SQL查詢將該信息轉換為此:

Brand    AA     AAA     C       D
BiGNRG   3      1       0       0
EcoBatt  0      0       2       0
LongLife 0      2       0       1

我不知道如何將這些數據轉換為這種格式。

如果選項的數量有限,則可以嘗試通過取消選擇union all來使用組

select brand, count(AA) AA, count(AAA)  AAA, count(C) C, count(D) D 
from (
    select  Brand, 'AA' AA ,  NULL  AAA,  NULL C , NULL D 
    from my_table 
    where size ='AA'
    union ALL 
    select  Brand, null ,  'AAA'  ,  NULL , NULL
    from my_table 
    where size ='AAA'
    union ALL 
    select  Brand, null ,  null   ,  'C' , NULL
    from my_table 
    where size ='C'
    union ALL 
    select  Brand, null ,  null   , null,  'D'
    from my_table 
    where size ='D'
) T 
group by brand 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM