我有一个表格,显示项目进入和退出仓库。摄像机1和摄像机2分别记录该项目的进入时间和退出时间。然后摄像机在物品进入时对物品进行分类,并在激光的帮助下离开检查点。例如:大盒子:5级,中型盒子:3级,小盒子:2级。
有时,相机分类并不相互匹配。例如:入口处的分类可以是中等框,退出时可以是小框。
我需要查找班级与同一TransactionDetail
不匹配的交易数量,然后查找某些时间范围内所有交易中这些类别不匹配的百分比。
我的表看起来有点像这样:
---------------------------------------------------------------------------
| AVDetailID | TransDetailID | AVClassID | CamID | CreatedDate |
---------------------------------------------------------------------------
| 20101522 | 54125478 | 5 | 1 | 2017-05-08 10:15:01:560|
| 20101523 | 54125478 | 5 | 2 | 2017-05-08 10:15:01:620|
| 20101524 | 54125479 | 3 | 1 | 2017-05-08 10:15:03:120|
| 20101525 | 54125479 | 2 | 2 | 2017-05-08 10:15:03:860|
| 20101526 | 54125480 | 4 | 1 | 2017-05-08 10:15:06:330|
| 20101527 | 54125480 | 4 | 2 | 2017-05-08 10:15:06:850|
---------------------------------------------------------------------------
因此,在上面的例子中,类在记录3和4中从3变为2.这是类更改的一个事务。我需要获得每个摄像机之间班级变化的所有交易的百分比。
到目前为止,我尝试过的代码是失败的:
SELECT
COUNT(TransDetailId)
FROM
[AVTransDetail]
WHERE
((SELECT AVCClassId WHERE CamId = 1) <> (SELECT AVCClassId WHERE DetectionZoneId = 2))
AND CreatedDate >= '2017-04-01'
AND CreatedDAte <= '2017-04-07'
GROUP BY
TransDetailId
答案 0 :(得分:1)
您可以尝试像这样加入表格:
SELECT tdBefore.TransDetailId
FROM AVTransDetail AS tdBefore
INNER JOIN AVTransDetail AS tdAfter
ON tdBefore.TransDetailID = tdAfter.TransDetailID
AND tdBefore.CamID = 1
AND tdAfter.CamID = 2
WHERE tdBefore.AVClassID <> tdAfter.AVClassID
AND tdBefore.CreatedDate >= '2017-04-01'
AND tdAfter.CreatedDate <= '2017-04-07'
然后获得百分比:
DECLARE @MinDate DATE = '20170401',
@MaxDate DATE = '20170407';
SELECT tdBefore.TransDetailId,
COUNT(tdAfter.TransDetailID) OVER() AS NumDifferent,
((CONVERT(DECIMAL(3, 2), COUNT(tdAfter.TransDetailID) OVER())) / allRecords.Count) * 100 AS DiffPercent,
FROM AVTransDetail AS tdBefore
INNER JOIN AVTransDetail AS tdAfter
ON tdBefore.TransDetailID = tdAfter.TransDetailID
AND tdBefore.CamID = 1
AND tdBefore.CamID = 2
CROSS APPLY
(
SELECT COUNT(*) AS [Count]
FROM AVTransDetail
WHERE tdBefore.CreatedDate >= @MinDate
AND tdAfter.CreatedDate <= @MaxDate
) AS allRecords
WHERE tdBefore.AVClassID <> tdAfter.AVClassID
AND tdBefore.CreatedDate >= @MinDate
AND tdAfter.CreatedDate <= @MaxDate