我有保存deleieverddate的表,其中一些交付日期爲空,其中一些不是我想計算交割日期爲空的計數並跳過日期那些在兩者之間錯過的人。Sql計算大於列值的計數
即
deleievered date
NULL
NULL
NULL
數量應爲3
即
NULL
NULL
9/22/2017
NULL
10/22/2017
NULL
計數應該是1 這裏跳過所有以前這裏deievered日期不爲空
我有試過這個,但它太昂貴了。
DECLARE @myTable TABLE
(
MessageId BIGINT ,
ReceiverID VARCHAR(100)
)
DECLARE @mySecondTable TABLE
(
MessageId BIGINT ,
ReceiverID VARCHAR(100),
DeliveredDate DATETIME
)
DECLARE @myLastTable TABLE
(
MessageId BIGINT ,
ReceiverID VARCHAR(100)
)
INSERT INTO @myTable
(MessageId ,
ReceiverID
)
SELECT MAX(MessageID) ,
ReceiverID
FROM dbo.CM_MessageStatus
WHERE ReceiverID IN (SELECT *
FROM string_split(@UserID, ','))
AND DeliveredDate IS NOT NULL
GROUP BY ReceiverID
INSERT INTO @mySecondTable
(MessageId ,
ReceiverID,
DeliveredDate
)
SELECT CM_MessageStatus.MessageID,
dbo.CM_MessageStatus.ReceiverID,
DeliveredDate
FROM dbo.CM_MessageStatus
WHERE DeliveredDate IS NULL AND
ReceiverID IN (SELECT *
FROM string_split(@UserID, ','))
--GROUP BY dbo.CM_MessageStatus.ReceiverID,DeliveredDate
--Now check each userid
declare @ReceiverID NVARCHAR(MAX)
while exists (select * from @mySecondTable)
BEGIN
select top 1 @ReceiverID = ReceiverID
from @mySecondTable
order by ReceiverID ASC
IF EXISTS(SELECT * FROM @myTable WHERE [email protected])
BEGIN
INSERT INTO @myLastTable
(MessageId ,
ReceiverID
)
SELECT MessageID,
@ReceiverID
FROM @mySecondTable
WHERE DeliveredDate IS NULL
AND MessageId > (SELECT
MessageId
FROM
@myTable
WHERE
ReceiverID = @ReceiverID
)
AND [email protected]
--GROUP BY ReceiverID
END
ELSE
BEGIN
INSERT INTO @myLastTable
(MessageId ,
ReceiverID
)
SELECT MessageID ,
ReceiverID
FROM @mySecondTable
WHERE DeliveredDate IS NULL
AND [email protected]
END
delete @mySecondTable
where ReceiverID = @ReceiverID
END
SELECT COUNT(MessageId) AS MessageId,ReceiverID FROM @myLastTable
GROUP BY ReceiverID
80秒花了35秒,這太昂貴了,我怎麼能在一個選擇中做到這一點。努力是分享這個問題。
您的記錄排序對於此邏輯似乎非常重要。你如何確定訂單? – JNevill
我不要去訂購方向? – bilal
你的數據的排序是什麼?交貨日期是否總是大於上一行?如果沒有,是否有ID列或代表數據序列的東西?像MessageId也許? – scsimon