简体   繁体   English

如何在 laravel 查询生成器中获取列具有最高值且另一列具有特定值的行

[英]How to get rows where a column has highest value and another column has a specific value in laravel query builder

╔════╦═══════╦═══════╦═══════╗
║ id ║ Col A ║ Col B ║ Col C ║
╠════╬═══════╬═══════╬═══════╣
║ 1  ║ 36    ║ 50    ║ AAA   ║
║ 2  ║ 36    ║ 50    ║ BBB   ║
║ 3  ║ 36    ║ 44    ║ CCC   ║
║ 4  ║ 36    ║ 44    ║ DDD   ║
║ 5  ║ 56    ║ 33    ║ EEE   ║
║ 6  ║ 56    ║ 78    ║ FFF   ║
╚════╩═══════╩═══════╩═══════╝

How to use laravel query builder to get table rows where highest number in 'Col B' and in same value 'Col A'?如何使用 laravel 查询生成器获取“Col B”中数字最高且“Col A”值相同的表行?

In the end, I hope to get the result like:最后,我希望得到如下结果:

╔════╦═══════╦═══════╦═══════╗
║ id ║ Col A ║ Col B ║ Col C ║
╠════╬═══════╬═══════╬═══════╣
║ 1  ║ 36    ║ 50    ║ AAA   ║
║ 2  ║ 36    ║ 50    ║ BBB   ║
║ 6  ║ 56    ║ 78    ║ FFF   ║
╚════╩═══════╩═══════╩═══════╝

the reason why getting these row is because in 'Col A' have two number 36 & 56. The highest number in 'Col B' is 50 for 36, and The highest number in 'Col B' is 78 for 56.获得这些行的原因是因为在“Col A”中有两个数字 36 和 56。“Col B”中的最高数字是 36 的 50,“Col B”中的最高数字是 56 的 78。

Here is SQL query to fulfill your requirement:这是 SQL 查询以满足您的要求:

SELECT * FROM `test` WHERE col_b in (SELECT MAX(col_b) from test GROUP BY col_a);

Consider test as your table name, col_a and col_b as Col A and Col B respectively.test作为您的表名, col_acol_b分别作为 Col A 和 Col B。

Below is Laravel Query builder version of the above query:以下是上述查询的 Laravel 查询生成器版本:

Test::select('*')
        ->whereIn('col_b', function($query)
        {
           $query->from('test')->select(DB::raw("MAX(col_b)"))->groupBy('col_a');
        })->get();

Hope it works for you.希望对你有效。 :) :)

I am uncertain if you need help with Laravel Query Builder or developing the query logic.我不确定您是否需要 Laravel 查询生成器或开发查询逻辑的帮助。 Here is the query logic that will work in SQL Server.这是将在 SQL 服务器中工作的查询逻辑。 The concepts apply across all RDBMSs.这些概念适用于所有 RDBMS。

select a.id
, a.[Col A]
, a.[Col B]
, a.[Col C]
from TblA a
  inner join (
    select [Col A]
    , max([Col B]) as 'Col B'
    from TblA
    group by [Col A]
  ) b on b.[Col A] = a.[Col A]
     and b.[Col B] = a.[Col B]

Then you can use the correct answer from another post to convert that to use in Laravel Query Builder.然后,您可以使用另一篇文章中的正确答案将其转换为在 Laravel 查询生成器中使用。

Try this:尝试这个:

$result = DB::table('your_table')
        ->whereIn('your_table.col_b', function($query) {
            $query->from('your_table')
                  ->select(DB::raw("MAX(col_b)"))
                  ->groupBy('col_a');
        })->get();

dd($result);

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM