获取最大值

时间:2015-06-12 06:15:09

标签: sql

   TABLE Laptop_Shift_Departments 

   id     Laptop_ID  Curr_department    Pre_Department
    -----|----------|-----------------|----------------
    9        71            4                 3
    10       68            4                 3
    11       71            5                 4
    12       68            5                 4

用户仅搜索采购订单编号,并且针对此PO_Num,有2台笔记本电脑(Laptop_ID)

上面是我的表格现在我希望得到MAX值对照这个laptop_ID ID

我试过这个:

    SELECT LD.ID AS  Laptop_ID,ld.GulfITBarcode,po.ID as PO_ID,PO.PO_Number as PO_Number,D.Department,
    D.ID as Crr_DepID1,d2.Department,D2.ID as Pre_DepID2  
    FROM PO_PURCHASEORDER PO
        INNER JOIN PO_Laptop_Master LM
        ON LM.PO_ID = PO.ID
        INNER JOIN PO_LaptopDetail LD
        ON LD.LapTop_Master_ID = LM.ID
        INNER JOIN Laptop_Shift_Departments DP
        ON DP.Laptop_Detail_ID = LD.ID
        inner join Laptop_Departments d
        on d.ID = DP.Current_Dep_ID
        inner join Laptop_Departments d2
        on d2.ID = DP.Previous_Dep_ID
        WHERE PO_NUMBER = '5258'
        AND
        LD.ID IN (select Max(cSh.id) from Laptop_Shift_Departments cSh)

但它不起作用

我的输出应该是这样的:

id     Laptop_ID  Curr_department    Pre_Department
-----|----------|-----------------|----------------
11       71            5                 4
12       68            5                 4

1 个答案:

答案 0 :(得分:0)

您想要使用' Group By'功能位于您要分组的字段的末尾,并且' Max'功能在您想要的列上选择' Max' (或者' Min'或者' Avg')。应该看起来像这样:

SELECT 
     LD.ID AS  Laptop_ID
    ,ld.GulfITBarcode
    ,po.ID as PO_ID
    ,PO.PO_Number as PO_Number
    ,D.Department
    ,MAX(D.ID) as Crr_DepID1
    ,d2.Department
    ,MAX(D2.ID) as Pre_DepID2  
FROM PO_PURCHASEORDER PO
    INNER JOIN PO_Laptop_Master LM
        ON LM.PO_ID = PO.ID
    INNER JOIN PO_LaptopDetail LD
        ON LD.LapTop_Master_ID = LM.ID
    INNER JOIN Laptop_Shift_Departments DP
        ON DP.Laptop_Detail_ID = LD.ID
    inner join Laptop_Departments d
        on d.ID = DP.Current_Dep_ID
    inner join Laptop_Departments d2
        on d2.ID = DP.Previous_Dep_ID
WHERE PO_NUMBER = '5258'
    AND LD.ID IN (select Max(cSh.id) from Laptop_Shift_Departments cSh)
    AND DP.Current_Dep_ID = 5
GROUP BY
     LD.ID 
    ,ld.GulfITBarcode
    ,po.ID 
    ,PO.PO_Number 
    ,D.Department
    ,d2.Department

(还没有看到表结构,我不确定查询的其余部分。希望这会有所帮助。)