我试图弄清楚如何从SQL Server过滤数据集。
DECLARE @OUTPUT AS TABLE (FILTER INT,PART INT,LOT INT)
INSERT INTO @OUTPUT (FILTER,PART,LOT) VALUES
(1,1377882157,1379436702),
(1,1377882157,1382038239),
(1,1377882157,1382038531),
(3,1373463498,1380792160),
(3,1377882157,1379436702),
(4,1373638746,1382475541),
(4,1377882157,1379436702),
(5,1373463498,1380792160),
(5,1373463959,1380792272),
(5,1373464034,1380791899),
(5,1373638746,1379326622),
(5,1373638746,1382475541),
(5,1373638756,1383222295),
(5,1377882157,1379436702),
(5,1377882157,1382038239),
(5,1377882157,1382038531),
(5,1377882159,1383658054),
(8,1373638746,1379326622),
(8,1377882157,1379436702)
我正在寻找PART& LOT存在于每个过滤器组中。过滤器组是根据用户选择动态生成的。
提供的数据只返回1个项目(例如1377882157,1379436702),因为它是所有过滤器组中唯一存在的项目。
这就是我现在所拥有的......想知道是否有更好的方法可以做到这一点?
DECLARE @FILTER_CNT INT
SET @FILTER_CNT = 5
SELECT
F_PART,
F_LOT
FROM @FILTERED_LOTS
GROUP BY F_PART,F_LOT
HAVING COUNT(FILTER) = @FILTER_CNT
我不需要定义FILTER_CNT的方法正是我的想法。
答案 0 :(得分:2)
您可以使用子查询替换@FILTER_CNT
SELECT PART, LOT
FROM output
GROUP BY PART, LOT
HAVING COUNT(FILTER) =
(
SELECT COUNT(DISTINCT FILTER)
FROM output
)
输出:
| PART | LOT | |------------|------------| | 1377882157 | 1379436702 |
这是 SQLFiddle 演示
答案 1 :(得分:0)
--DECLARE @FILTER_CNT INT
--SET @FILTER_CNT = 5
use this instead
SELECT
PART,
LOT,count(FILTER) as FILTER_total_count
FROM @OUTPUT
GROUP BY PART,LOT
HAVING COUNT(FILTER)=(select count(distinct FILTER) from @OUTPUT)