连接和分组来自3个表的数据

时间:2014-07-23 13:04:08

标签: sql join group-by

我有两张桌子

分类

CategorySerno | CategoryName 
      1            One 
      2            Two
      3            Three

状态

StatusSerno | Status
1              Active
2              Pending

数据

CatId |Status |    Date
1       1          2014-07-26 11:30:09.693
2       2          2014-07-25 17:30:09.693
1       1          2014-07-25 17:30:09.693
1       2          2014-07-25 17:30:09.693

当我加入他们时,我得到了我需要加入最新日期/ 像

One   Active    2014-07-26 11:30:09.693
Two   Inactive  2014-07-25 17:30:09.693
Three  Null      Null

当我进行加入并将它们分组时它给了我

 One   Active    2014-07-26 11:30:09.693
 One   Active    2014-07-26 11:30:09.693
 One   Active    2014-07-26 11:30:09.693
 Two   Inactive  2014-07-25 17:30:09.693
 Three Null       Null

4 个答案:

答案 0 :(得分:0)

您可以在CTE中使用ROW_NUMBER

WITH CTE AS
(
    SELECT c.CategoryName, 
           s.Status,
           d.Date,
           dateNum = ROW_NUMBER() OVER (PARTITION BY CatId, d.Status 
                                        ORDER BY Date DESC)
    FROM Category c 
    LEFT OUTER JOIN Data d
        ON c.CategorySerno = d.CatId 
    LEFT OUTER JOIN Status s
        ON d.Status = s.StatusSerno 
)
SELECT CategoryName, Status, Date
FROM CTE
WHERE dateNum = 1

Demo-Fiddle

答案 1 :(得分:0)

您可能在SELECT和GROUP BY列之间存在不匹配的错误重复

试试这个:

SELECT Category.CategoryName, Status.Status, MAX(Data.Date) Data
FROM Data
LEFT JOIN Category ON Category.CategorySerno = Data.CatId
LEFT JOIN Status ON Status.StatusSerno = Data.Status
GROUP BY Category.CategoryName, Status.Status

答案 2 :(得分:0)

您没有提到您正在使用的RDBMS,但您可能会尝试使用以下内容:

SELECT
    c.CategoryName
,   s.Status
,   d.Date
FROM
    Data                     d
    LEFT OUTER JOIN Category c ON d.CatId  = c.CategorySerno
    LEFT OUTER JOIN Status   s ON d.Status = s.StatusSerno
WHERE
    d.date=(
        SELECT
            max(dd.date)
        FROM
            Data dd
        WHERE
            d.CatId  = dd.CatId
            AND  
            d.Status = dd.Status
    ) z

为了使其在长期运行中更易于维护,请考虑使用约定来标识任何表中的主键,例如table_name_id,并对外键使用相同的约定。使用此约定解决了以下问题:是“CategorySerno”还是“CatId”?

答案 3 :(得分:0)

SELECT CategoryName, Status.Status, MAX(Data.Date) FROM Category 
LEFT OUTER JOIN Data ON CategorySerno = CatId 
LEFT OUTER JOIN Status ON Data.Status = Status.StatusSerno 
GROUP BY CategoryName, Status.Status