2

我想弄清楚如何从 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 的方法。

4

2 回答 2

2

您可以@FILTER_CNT用子查询替换

SELECT PART, LOT
  FROM output
 GROUP BY PART, LOT
HAVING COUNT(FILTER) = 
(
  SELECT COUNT(DISTINCT FILTER) 
    FROM output
)

输出:

| 部分 | 很多 |
|------------|------------|
| 1377882157 | 1379436702 |

这是SQLFiddle演示

于 2013-11-08T04:51:37.233 回答
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)
于 2013-11-08T04:50:55.533 回答