T-SQL,省略不必要的结果

时间:2011-04-08 19:28:33

标签: tsql sql-server-2008

CREATE TABLE #t(LocationCode varchar(10), ResourceId int, TransType char(3))

INSERT #t
SELECT 'STORE 001', 1, 'In' UNION ALL

SELECT 'STORE 002', 2, 'In' UNION ALL

SELECT 'STORE 003', 3, 'In' UNION ALL

SELECT 'STORE 001', 1, 'Out' UNION ALL
SELECT 'STORE 004', 1, 'In'  UNION ALL

SELECT 'STORE 004', 4, 'In' UNION ALL
SELECT 'STORE 004', 4, 'Out' UNION ALL

SELECT 'STORE 004', 1, 'Out' UNION ALL
SELECT 'STORE 001', 1, 'In'  

DROP TABLE #t

与“Outs”相比,如何仅显示具有最大数量“Ins”的相应位置的项目(对不起我的英语不好)。

LocationCode              ResourceId
STORE 001[edited]         1
STORE 002                 2
STORE 003                 3

1 个答案:

答案 0 :(得分:6)

假设你只想要Ins没有匹配的Out。

SELECT *
FROM #t AS a
WHERE a.TransType = 'In'
    AND NOT EXISTS (
        SELECT *
        FROM #t AS b
        WHERE b.TransType = 'Out'
            AND b.LocationCode = a.LocationCode
            AND b.ResourceId = a.ResourceId
    )

您的架构中需要更多数据才能将Out与In匹配。

尝试更简单的事情:

SELECT LocationCode, ResourceID
FROM #t
GROUP BY LocationCode, ResourceID
HAVING COUNT(*) % 2 = 1

以下是对事务进行排序的示例以及使用该序列的两种方法:

CREATE TABLE #t(LocationCode varchar(10), ResourceId int, TransType char(3), Seq int UNIQUE NOT NULL)

INSERT #t
SELECT 'STORE 001', 1, 'In', 1 UNION ALL
SELECT 'STORE 002', 2, 'In', 2 UNION ALL
SELECT 'STORE 003', 3, 'In', 3 UNION ALL
SELECT 'STORE 001', 1, 'Out', 4 UNION ALL
SELECT 'STORE 004', 1, 'In', 5 UNION ALL
SELECT 'STORE 004', 4, 'In', 6 UNION ALL
SELECT 'STORE 004', 4, 'Out', 7 UNION ALL
SELECT 'STORE 004', 1, 'Out', 8 UNION ALL
SELECT 'STORE 001', 1, 'In', 9 

;WITH Ins AS (
SELECT * FROM #t
WHERE TransType = 'In'
)
,Outs AS (
SELECT * FROM #t
WHERE TransType = 'Out'
)
,Matched AS (
SELECT *,
(SELECT MIN(Seq)
FROM Outs
WHERE Outs.LocationCode = Ins.LocationCode
AND Outs.ResourceID = Ins.ResourceID
AND Outs.Seq > Ins.Seq) AS OutSeq
FROM Ins
)
SELECT *
FROM Matched
WHERE OutSeq IS NULL

;WITH LastIn AS (
SELECT ResourceID, MAX(Seq) AS Seq
FROM #t
WHERE TransType = 'In'
GROUP BY ResourceID
)
SELECT *
FROM LastIn
WHERE NOT EXISTS (
SELECT *
FROM #t outs
WHERE outs.TransType = 'Out'
AND Outs.ResourceID = LastIn.ResourceID
AND outs.Seq > LastIn.Seq)

DROP TABLE #t​​​​​​​​​​​