gpt4 book ai didi

mysql - 按组统计字段数据库

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:00 24 4
gpt4 key购买 nike

表格顺序

id_order | date    | id_product | id_size | id_gender | name |
1 |2012-1-1 | 1 | 1 | 1 | john |
2 |2012-1-1 | 1 | 2 | 1 | mayer|
3 |2012-1-1 | 2 | 1 | 1 | chris|

标签产品

id_shirt |  name   |
1 | jeans |
2 | shirt |
3 | jacket |

标签大小

id_size  |  size  |
1 | S |
2 | M |
3 | L |
4 | XL |

如果性别是男性,我会产生这样的结果。

name  |  S  |  M  |  L  |  XL  |
jeans | 2 | | | |
shirt | | 1 | | |

请在codeigniter代码中查询。

最佳答案

SELECT  b.name,
SUM(CASE WHEN c.size = 'S' THEN 1 ELSE 0 END) S,
SUM(CASE WHEN c.size = 'M' THEN 1 ELSE 0 END) M,
SUM(CASE WHEN c.size = 'L' THEN 1 ELSE 0 END) L,
SUM(CASE WHEN c.size = 'XL' THEN 1 ELSE 0 END) XL
FROM orderTB a
INNER JOIN productTB b
ON a.id_product = b.id_shirt
INNER JOIN sizeTB c
ON a.id_size = c.id_size
GROUP BY b.name

或者,如果您有未知的大小值,则动态 SQL 更为可取,例如

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN c.size = ''',
size,
''' THEN 1 ELSE 0 END) AS ',
size
)
) INTO @sql
FROM sizeTB;

SET @sql = CONCAT('SELECT b.name, ', @sql, '
FROM orderTB a
INNER JOIN productTB b
ON a.id_product = b.id_shirt
INNER JOIN sizeTB c
ON a.id_size = c.id_size
GROUP BY b.name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

关于mysql - 按组统计字段数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14109427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com