几周前我问过这里发布的问题,现在球门柱略有变动:
我发现SuppressionType具有优先级,计数应按降序优先级进行。出现的问题是一些supressions具有相同的优先级,在这种情况下,SuppressionTypeID应该按降序使用以产生不同的顺序。
为了解决这个问题,我计算了多个文件中的不同行,因此是fileid。
我对sql的理想结果是:
SuppressionTypeID FileID PersonCount
1 8786 2
2 8976 1
2 8977 1
我正在使用的演示代码(来自上一个问题):
create table #t (
ID INT
,SuppressionTypeID INT
,priority int
,PersonID INT
,fileid int
)
INSERT INTO #t
SELECT 1
,1
,1
,123
,8976
UNION ALL
SELECT 2
,1
,1
,456
,8786
UNION ALL
SELECT 3
,2
,1
,456
,8976
UNION ALL
SELECT 4
,2
,1
,789
,8976
UNION ALL
SELECT 5
,2
,1
,123
,8977
create table #t1 (
ID INT
,SuppressionTypeID INT
,Priority int
,PersonID INT
,FileID int
,firstid INT
)
INSERT INTO #t1
SELECT *
,NULL
FROM #t
UPDATE t1
SET t1.firstid = t2.firstid
FROM #t1 AS t1
JOIN (
SELECT personid
, min(SuppressionTypeID) AS firstid
, FileID
FROM #t1
GROUP BY FileID, PersonID, Priority
) AS t2 ON t1.PersonID = t2.PersonID
AND t2.fileid = t1.FileID
SELECT coalesce(t2.firstid, t1.SuppressionTypeID) AS SuppressionTypeID
, t1.FileID
, count(DISTINCT t2.personid) AS PersonCount
FROM #t1 AS t1
LEFT JOIN #t1 AS t2 ON t1.personid = t2.personid
AND t1.SuppressionTypeID = t2.firstid
GROUP BY coalesce(t2.firstid, t1.SuppressionTypeID), t1.FileID
Order by t1.FileID, coalesce(t2.firstid, t1.SuppressionTypeID)
只要结果正确,只要有更好的方法,就不必使用此apporach。
提前致谢
我也一直试试这个。我试图得到1的等级,从那里我可以计算排名= 1的位置,但这不是很有效:
;WITH CTE AS (
SELECT SuppressionTypeID
, FileID
, PersonID
, [Priority]
, RANK() OVER (PARTITION BY FileID, [Priority], PersonID ORDER BY SuppressionTypeID) AS FirstID
FROM #t
)
SELECT * FROM CTE
理想情况下,我的结果是:
SuppressionTypeID FileID PersonID Priority FirstID
1 8786 456 1 1
1 8976 123 1 1
2 8976 456 1 2
2 8976 789 1 1
2 8977 123 1 1
2 8977 456 1 1
答案 0 :(得分:0)
尝试将sql拆分为部分并构建:
根据SuppressionID,FileID ...优先级
,每个PersonID将获得一个实例SELECT * FROM
(SELECT *, Row_Number() OVER (partition by PersonID ORDER By SuppressionTypeID,...) AS RN FROM #T) A
WHERE RN = 1
然后将其用作Count查询的源。