我有一张表int get_input(int* x, int* y) {
char* p, buf[LINE_MAX];
int n1, n2;
printf("Prompt: ");
fgets(buf, sizeof(buf), stdin);
n1 = strtol(buf, &p, 10);
if (p == buf || *p != '\n') {
return 0;
}
n2 = strtol(buf, &p, 10);
if (p == buf || *p != '\n') {
return 0;
}
*x = n1;
*y = n2;
return 1;
}
int main(int argc, char** argv) {
int x, y;
if (get_input(&x, &y)) {
printf("Worked: %d %d\n", x, t);
} else {
printf("Invalid\n");
}
return 0;
}
和一张表Customers
。客户可以拥有多个客户卡。表Customercards
使用customer_id引用客户。
我想写一个查询来计算每个客户的客户卡数,并打印出结果,按卡数分组,如下所示:
Customercards
目前,我有一个查询,使用cards count
0 50
1 37
2 13
3 5
4 1
和group by
计算具有指定卡数的客户。但我必须多次使用此查询来计算不同数量的客户卡。例如:
having
有没有办法将其放入一个查询中?
答案 0 :(得分:1)
我称之为"直方图的直方图"查询。您可以使用两个聚合:
SELECT cnt, COUNT(*), MIN(customer_id), MAX(customer_id)
FROM (SELECT c.customer_id, COUNT(*) as cnt
FROM CUSTOMERS c JOIN
CUSTOMERCARDS cc
ON c.customer_id = cc.customer_id
GROUP BY c.customer_id
) c
GROUP BY cnt
ORDER BY cnt;
我包含了最小和最大客户ID,因为我发现在进行此类查询时会有示例。
注意:您实际上并不需要JOIN
,因此您可以将其简化为:
SELECT cnt, COUNT(*), MIN(customer_id), MAX(customer_id)
FROM (SELECT cc.customer_id, COUNT(*) as cnt
FROM CUSTOMERCARDS cc
GROUP BY cc.customer_id
) c
GROUP BY cnt
ORDER BY cnt;