dtn55928 2016-08-05 07:03
浏览 158
已采纳

SQL SELECT仅包含两个不同表中列的MAX值的行

My two table setup is like below:

table1

+------+---------+--------------------------------------+
| id   | tail    | content                              |
+------+---------+--------------------------------------+
| 1    | abc     | ...                                  |
| 2    | def     | ...                                  |
| 3    | ghi     | ...                                  |
| 4    | def     | ...                                  |
| 5    | jkl     | ...                                  |
+------+-------+----------------------------------------+

table2

+------+--------+---------------------------------------+
| id   | tailID | value   |  others                     |
+------+--------+---------------------------------------+
| 1    | 2      | 412     |                             |
| 2    | 3      | 215     |                             |
| 1    | 2      | 571     |                             |
| 1    | 4      | 123     |                             |
+------+--------+---------------------------------------+

I like to get all columns from this two tables in a row with matched tail = tailID but not duplicate rows which has same tail.

For the duplicate TAIL, just need to get the single row of max VALUE of same tail.

I am currently using

SELECT table1.tail, table2.other_column 
FROM table1 
INNER JOIN table2 
on table1.id = table2.tailID 
WHERE table1.some_coloum = "a sepecific string" 
ORDER BY table2.value

But it returns many duplicates of same tail.

I just need to have single row for duplicate TAIL with hightes VALUE of table2.

  • 写回答

3条回答 默认 最新

  • duanguzhong5776 2016-08-05 07:24
    关注

    DISTINCT with CROSS APPLY:

    SELECT DISTINCT t1.tail,
                    t2.other_column,
                    t3.[value]
    FROM table1 t1
    CROSS APPLY (
        SELECT  tailid,
                MAX([value]) as [value]
        FROM table2
        WHERE tailid = t1.id
        GROUP BY tailid
        ) as t3
    INNER JOIN table2 t2
        ON t2.tailid = t3.tailid AND t3.[value] = t2.[value]
    WHERE t1.some_coloum = "a sepecific string" 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能