我很困惑在SQL中使用AS查看三种情况,这是我的表
id | Fruit
___________
1 | Apel
2 | Orange
3 | Apel
4 | Manggo
___________
这是我的第一个查询:
SELECT
COUNT(fruit) AS apelfruit
FROM fruit_table
WHERE fruit = 'Apel'
输出:
apelfruit
_________
2
但是当我这样做时:
SELECT
COUNT(fruit) AS apelfruit,
COUNT(fruit) AS orangefruit,
COUNT(fruit) AS manggofruit
FROM fruit_table
WHERE fruit = 'Apel'
AND fruit = 'Orange'
AND fruit = 'Manggo'
输出为零(0):
apelfruit | orangefruit | manggofruit
____________________________________
0 0 0
我有点困惑什么错。任何人都可以帮助我,我将不胜感激。谢谢。
答案 0 :(得分:1)
尝试以下方式
SELECT
sum(case when fruit = 'Apel' then 1 else 0 end) AS apelfruit,
sum(case when fruit = 'Orange' then 1 else 0 end) AS orangfruit,
sum(case when fruit = 'Manggo' then 1 else 0 end) AS manggofruit
FROM fruit_table
答案 1 :(得分:1)
为简洁起见,我更喜欢在这里使用COUNT
:
SELECT
COUNT(CASE WHEN fruit = 'Apel' THEN 1 END) AS apelfruit,
COUNT(CASE WHEN fruit = 'Orange' THEN 1 END) AS orangfruit,
COUNT(CASE WHEN fruit = 'Manggo' THEN 1 END) AS manggofruit
FROM fruit_table;
正如@nicomp指出的那样,以这种方式进行数据透视查询的局限性在于,输出中出现的列是硬编码的,并且必须添加更多代码以进行新的条件计数。但是,解决此问题的唯一真正方法是使用动态SQL。
答案 2 :(得分:0)
条件是您遇到的问题是水果不能等于“ apel”,“ ”和 它应该是“ apel” 或“ apel”
由于只计算水果,将始终计算所有水果,因此,您还需要使用一个条件进行计数,在此解决方案中,根据条件求和1或0:
this.selectedFilters$ = merge(
this.filter$.pipe(
switchMap((allFilters) => {
return of({
itemId: allFilters[0].itemId,
filterOptions: this.getDefaultFilterOptions(allFilters)
});
}),
),
this.newFilter$.pipe(
switchMap((newFilter: FilterOption) => {
return of(this.getNewFilterOptions(newFilter, this.currentFilters));
}),
)
).pipe(tap((filters) => this.currentFilters = filters));
}
// LESS IMPORTANT CODE BELOW...
private getNewFilterOptions(newFilter: FilterOption, currentFilters: ItemFilter): ItemFilter {
const changedFilter = currentFilters.filterOptions.findIndex(f => f.filterId === newFilter.filterId);
currentFilters.filterOptions[changedFilter] = newFilter;
return currentFilters;
}
private getDefaultFilterOptions(filters: ItemFilter[]): FilterOption[] {
return filters.reduce((acc, item) => acc.concat(item.filterOptions[0]), []);
}