来自不同表的复杂数据

时间:2018-10-03 13:38:15

标签: mysql

我需要找到2004年第一季度销售额最高的员工...

我尝试了很多方法,但是它太复杂了。有人介意帮我吗?

到目前为止,我有:

// Restore state, search and column level filter
    var state = table.state.loaded();
    if (state) {
        table.columns().eq(0).each(function (colIdx) {
            var colSearch = state.columns[colIdx].search;

            if (colSearch.search) {
                $('input', table.column(colIdx).header()).val(colSearch.search);
            }
        });

        table.draw();
    }


    // Apply the search
    table.columns().eq(0).each(function (colIdx) {
        $('input', table.column(colIdx).header()).on('keyup change', function () {
            table
                .column(colIdx)
                .search(this.value)
                .draw();
        });
    });

谢谢!

1 个答案:

答案 0 :(得分:1)

  • 根据表之间的关系(如图所示)在各个表之间进行联接
  • 使用Sum()函数为一个employeeNumber组计算总销售额。
  • 按总销售额按降序排序,并使用LIMIT 1来考虑总销售额最高的员工
  • 在您的where条件下使用日期函数,例如Year()Quarter(),以检查year = 2004quarter = 1

尝试以下操作:

SELECT e.employeeNumber, 
       e.firstName, 
       e.lastName, 
       SUM(od.quantityordered * od.priceEach) AS total_sales 
FROM orders AS o 
JOIN orderdetails AS od ON o.OrderNumber = od.OrderNumber 
JOIN customers AS c ON c.customerNumber = o.customerNumber 
JOIN employees AS e ON e.employeeNumber = c.salesRepEmployeeNumber 
WHERE YEAR(o.orderDate) = 2004 
  AND QUARTER(o.orderDate) = 1 
GROUP BY e.employeeNumber, e.firstName, e.lastName 
ORDER BY total_sales DESC LIMIT 1