序列化-在不同条件下对同一关联计数两次

时间:2018-09-20 18:57:42

标签: sql count associations sequelize.js

我试图根据不同的参数在关联的表中获取两个记录数:

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'] }) InvoicesInvoices的左外部联接。Customer = idInvoicesCustomerId。{{ 1}} = 0
  在Invoices上以isArchived的形式加入外部InvoicesInvoices = CustomeridInvoicesCustomerId = 0 AND InvoicesisArchived ='未付款'

是否可以为查询中的联接表指定其他名称?例如:

  

InvoicesstatusInvoices的左外部联接。Invoices = CustomeridInvoices。{{ 1}} = 0
  左外联接CustomerId Invoices 上的isArchivedInvoices = UnpaidInvoicesCustomer和{{1} }。id = 0和InvoicesCustomerId ='未付款'

1 个答案:

答案 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' ],
  ],
  // ...
},