我想计算A列中ID在B列中只有一个Distinct值的ID。
从编码的角度来说,我想:
SELECT Count(ID) WHERE ID has COUNT(DISTINCT(column_B_val) = 1
尝试使用代码IVE,在使用带聚合的where子句时出现错误
SELECT id FROM `x` WHERE COUNT(DISCTINCT(column_B_val)) = 1
答案 0 :(得分:0)
正确的sql如下所示
#define DECL_STACK_TYPE(type, name) \
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \
stk_##name stk_##name##_create(size_t init_size) { \
stk_##name s; if (!init_size) init_size = 4; \
s = malloc(sizeof(struct stk_##name##_t)); \
if (!s) return 0; \
s->buf = malloc(sizeof(type) * init_size); \
if (!s->buf) { free(s); return 0; } \
s->len = 0, s->alloc = init_size; \
return s; } \
int stk_##name##_push(stk_##name s, type item) { \
type *tmp; \
if (s->len >= s->alloc) { \
tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \
if (!tmp) return -1; s->buf = tmp; \
s->alloc *= 2; } \
s->buf[s->len++] = item; \
return s->len; } \
type stk_##name##_pop(stk_##name s) { \
type tmp; \
if (!s->len) abort(); \
tmp = s->buf[--s->len]; \
if (s->len * 2 <= s->alloc && s->alloc >= 8) { \
s->alloc /= 2; \
s->buf = realloc(s->buf, s->alloc * sizeof(type));} \
return tmp; } \
void stk_##name##_delete(stk_##name s) { \
free(s->buf); free(s); } \
type stk_##name##_get(stk_##name s) { \
type tmp; \
if (!s->len) abort(); \
tmp = s->buf[1]; \
return tmp; \
}
#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)
DECL_STACK_TYPE(char *, str)
void str_to_stk(char* input, stk_str output) {
while (input[0] != '\0') {
if (isdigit((input[0]))) {
int i = 0;
char* buffer = (char*) calloc(strlen(input)*sizeof(char),0);
while ((isdigit(input[i]) || input[i] == '.') && input[i] != '\0') {
strncat(buffer, &input[i], 1);
i++;
}
stk_str_push(output, buffer);
input = input+i;
free(buffer);
}
else if (isalpha(input[0])) {
int i = 0; char* buffer = (char*) calloc(strlen(input)*sizeof(char),0);
while (isalpha(input[i]) && input[i] != '\0') {
strncat(buffer, &input[i], 1);
i++;
}
stk_str_push(output, buffer);
input = input+i;
free(buffer);
}
else if (isoperator(input[0]) || input[0] == '(' || input[0] == ')') {
char buffer[2]; buffer[0] = input[0]; buffer[1] = '\0';
stk_str_push(output, buffer);
input = input+1;
}
else {
input++;
}
}
while (!stk_empty(output)) printf("%s\n", stk_str_pop(output));
}
void main() {
char *input = "321 AZERTY";
stk_str output = stk_str_create(20);
str_to_stk(input, output);
}
您不能在
处使用聚合答案 1 :(得分:0)
您可以使用两种聚合级别:
select count(*)
from (select id
from t
group by id
having count(distinct column_B_val) = 1
) t;
或者,not exists
:
select count(*)
from t
where not exists (select 1
from t t2
where t2.id = t.id and
t2.column_B_val <> t.column_B_val
);
在(id, column_B_val)
上有一个索引,这可能会有更好的性能。