我试图根据不同的参数在关联的表中获取两个记录数:
df_all = pd.read_csv(args.input)
df_all.set_index(df_all['Timestamp'])
ax = seaborn.heatmap(df_all, linewidth=0.5)
plt.show()
问题在于,当多次包含相同的关联表时,Sequelize会在SQL查询中为表的两个实例分配相同的名称:
在
// Models var Customer = sequelize.define('Customer', { name: DataTypes.STRING, }); var Invoice = sequelize.define('Invoice', { invoiceRef: DataTypes.STRING, status: { type: DataTypes.ENUM, values: ['UNPAID', 'PAID'], defaultValue: 'UNPAID' }, isArchived: { type: DataTypes.BOOLEAN, defaultValue: false }, }); Invoice.associate = function(models) { Invoice.belongsTo(models.Customer); } Customer.associate = function (models) { Customer.hasMany(models.Invoice); } // Query Customer.findAll({ attributes: { include: [ [models.Sequelize.fn("COUNT", models.Sequelize.fn("DISTINCT", models.Sequelize.col("Invoices.id"))), "totalInvoices"], [models.Sequelize.fn("COUNT", models.Sequelize.fn("DISTINCT", models.Sequelize.col("UnpaidInvoices.id"))), "unpaidInvoices"] ] }, include: [ { model: models.Invoice, where: { isArchived: false }, attributes: [], required: false }, { model: models.Invoice, where: { isArchived: false, status: 'UNPAID' }, attributes: [], required: false }, ], group: ['Customer.id'] })
上Invoices
上Invoices
的左外部联接。Customer
=id
。Invoices
和CustomerId
。{{ 1}} = 0
在Invoices
上以isArchived
的形式加入外部Invoices
。Invoices
=Customer
。id
和Invoices
。CustomerId
= 0 ANDInvoices
。isArchived
='未付款'
是否可以为查询中的联接表指定其他名称?例如:
在
Invoices
上status
上Invoices
的左外部联接。Invoices
=Customer
。id
和Invoices
。{{ 1}} = 0
左外联接CustomerId
按Invoices
上的isArchived
。Invoices
=UnpaidInvoices
。Customer
和{{1} }。id
= 0和Invoices
。CustomerId
='未付款'
答案 0 :(得分:1)
我通常只连接一次,然后在CASE
中使用SUM
语句,而不是使用COUNT
-所有行都被连接,这就是为什么两者都相同的原因。
attributes: {
include: [
// count paid using case/sum via `status` != 'UNPAID'
[ sequelize.fn('sum', sequelize.literal("CASE WHEN (`Invoices`.`status` != 'UNPAID' THEN 1 ELSE 0 END")), 'paid_count' ],
// count unpaid using case/sum via `status` = 'UNPAID'
[ sequelize.fn('sum', sequelize.literal("CASE WHEN (`Invoices`.`status` = 'UNPAID' THEN 1 ELSE 0 END")), 'unpaid_count' ],
],
// ...
},