Select 获取表中sum(a_int)=0、order by date和group by另一列的结果列
想象一张如下表: 唯一标识 专栏 b_柱 a_int 布因 创建日期 假设数据如下所示:Select 获取表中sum(a_int)=0、order by date和group by另一列的结果列,select,sql-server-2012,group-by,sum,partition,Select,Sql Server 2012,Group By,Sum,Partition,想象一张如下表: 唯一标识 专栏 b_柱 a_int 布因 创建日期 假设数据如下所示: -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
-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
我想得到唯一的_id s,其中b_int为1,b_column为333,考虑到a_column,a_int column必须始终为0,如果有a_int=1的记录,即使有a_int=0的记录,这些记录也不能显示在结果中。理想的结果是:3a33,6e66当按某个列分组并按创建日期排序时,每个唯一的a\u列都获得了top1
我尝试了很多关于联系和样本超额分配的方法,搜索了一些问题,但都没能做到。这就是我能做的:
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;
此查询返回的结果如下3a33、4d44、6e66。但是我不想要4d44。您使用分区和窗口功能的方法是正确的。此解决方案使用ROW_NUMBER为a_列指定一个值,以便我们可以看到其中有多个值。1是最新创建的日期。然后从结果集中选择行计数器为1的位置
;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