在某些数据库的表中使用一些SQL,我得到这样的结果:
id name date status
1 John 2018-05-03 PRESENT
2 Mary 2018-05-03 NOT PRESENT
3 Jane 2018-05-03 NOT PRESENT
2 Mary 2018-05-04 PRESENT
1 John 2018-05-04 PRESENT
1 John 2018-05-05 PRESENT
2 Mary 2018-05-05 NOT PRESENT
3 Jane 2018-05-04 PRESENT
3 Jane 2018-05-05 NOT PRESENT
1 John 2018-05-06 PRESENT
我想进一步使用SQL来获得类似这样的结果:
id name date present not present
1 John 2018-05 4 0
2 Mary 2018-05 1 2
3 Jane 2018-05 2 1
换句话说,我想根据他/她每天收到的状态来提取学生在给定月份中参加了多少课。我该如何实现?
我正在使用Postgresql数据库。
答案 0 :(得分:1)
使用conditional aggregation
:
select id, name, to_char(date,'YYYY-MM') as "Date",
sum(case when status = 'PRESENT' then 1 else 0 end ) as present,
sum(case when status = 'NOT PRESENT' then 1 else 0 end ) as not_present
from tab
group by id, name, "Date"
order by id
else 0
对于null
返回案例中获得0很重要列别名可能在group by
列表中使用
用于Postgres
由于需要的输出,将日期值截断为月
需要to_char(date,'YYYY-MM')
答案 1 :(得分:1)
"build:server:prod": "webpack --config webpack.server.prod.config.js",
"build:client:prod": "webpack --config webpack.client.prod.config.js",
"start:server:prod": "export NODE_ENV=production && node ./dist/server.*.js",
"start:iso:prod": "npm run build:client:prod && npm run build:server:prod && npm run start:server:prod"
答案 2 :(得分:0)
使用条件聚合(使用export const saveChosenCompany = (username, company) => dispatch => {
AsyncStorage.multiSet([
[`${username}.companyID`, company.id],
[`${username}.companyName`, company.name]
])
.then(() => {
dispatch({
type: SAVED_COMPANY,
payload: company
})
})
.catch(err => {
console.log(err);
dispatch({
type: SAVED_COMPANY,
payload: {
id: null,
name: null
}
})
})
}
export const initCompany = (company) => dispatch => {
dispatch({
type: INIT_COMPANY,
payload: company
})
}
)和filter
:
date_trunc()