获取 table 的列以获得 sum(a_int)=0 的结果并按日期排序并按另一列分组

Get column of table for results having sum(a_int)=0 and order by date and group by another column

想像下面的 table:

假设数据如下:

-unique_id   -a_column   -b_column     -a_int -b_int       -date_created
    1z23         abc          444          0      1     27.12.2016 18:03:00
    2c31         abc          444          0      0     26.12.2016 13:40:00
    2e22         qwe          333          0      1     28.12.2016 15:45:00
    1b11         qwe          333          1      1     27.12.2016 19:00:00
    3a33         rte          333          0      1     15.11.2016 11:00:00
    4d44         rte          333          0      1     27.09.2016 18:00:00
    6e66         irt          333          0      1     22.12.2016 13:00:00
    7q77         aaa          555          1      0     27.12.2016 18:00:00

我想获取 unique_id s,其中 b_int 为 1,b_column 为 333 并且考虑到 a_column,a_int 列必须始终为 0 ,如果有 a_int = 1 的记录,即使有 a_int = 0 的记录,这些记录也不得显示在结果中。期望的结果是:“ 3a33 , 6e66 ” 当按 a_column 分组并按 date_created 排序时,每个唯一 a_column 都获得 top1。

我尝试了很多 "with ties" 和 "over(partition by" 示例,搜索了问题,但无法做到。这是我能做的:

select unique_id 
from the_table 
where b_column = '333' 
  and b_int = 1 
  and a_column in (select a_column 
                   from the_table 
                   where b_column = '333'
                     and b_int = 1 
                   group by a_column
                   having sum(a_int) = 0) 
order by date_created desc;

这个查询returns结果是这样的“3a33,4d44,6e66”。但我不想要“4d44”。

您在分区和 window 函数方面走在了正确的轨道上。此解决方案使用 ROW_NUMBER 为 a_column 赋值,因此我们可以看到哪里有超过 1。1 是最近的 date_created。然后你从 row_counter 为 1 的结果集中 select。

;WITH CTE
AS (
    SELECT unique_id
        , a_column
        , ROW_NUMBER() OVER (
            PARTITION BY a_column ORDER BY date_created DESC
            ) AS row_counter --This assigns a 1 to the most recent date_created and partitions by a_column
    FROM #test
    WHERE a_column IN (
            SELECT a_column 
            FROM #test
            WHERE b_column = '333'
                AND b_int = 1
            GROUP BY a_column
            HAVING MAX(a_int) < 1
            )
    )
SELECT unique_ID
FROM cte
WHERE row_counter = 1