2

ユーザーによるモジュールのアクティブ化と非アクティブ化を記録するテーブルがあります。アクティブ化と非アクティブ化の間の時間差が最大であるテーブル内の行のみを選択したいと考えています。

user        activation           Deactivation     usage  dmb
Pejman   2005-10-04 14:02:00   2012-09-28 18:29:00   23   198
Pejman   2006-05-30 12:44:00   2012-09-28 18:29:00   34   198
Pejman   2009-11-18 11:06:00   2012-09-28 18:29:00   64   198
Shahin   2005-02-11 10:53:00   2012-09-28 18:29:00   52   323
Shahin   2012-06-24 08:35:00   2012-09-28 18:29:00   17   323
Shahin   2005-02-24 14:22:00   2006-01-16 09:03:00   19   323
Kazem    2008-01-21 22:32:00   2011-01-01 00:00:00   73   666
Kazem    2008-01-21 22:35:00   2012-09-28 18:29:00   62   666

私の望む出力

ユーザー

Pejman   2005-10-04 14:02:00   2012-09-28 18:29:00   23   198
Shahin   2005-02-11 10:53:00   2012-09-28 18:29:00   52   323
Kazem    2008-01-21 22:35:00   2012-09-28 18:29:00   62   666

期間(アクティブ化と非アクティブ化の違い)を見つけるには、次のSQLコード(MSSQL)を使用しています

 datediff(d,isnull(deactivation, getdate()), activation) AS Time_Difference

編集

私のテーブルは「with」操作の結果です。このような最初のテーブルを取得するという意味で、次のような他のクエリをいくつか書きました

with mytab_cte(user, editionID, size, CompanyName, cvr, postcode, agreement, ActivationT, DeactivationT) 
as 
( 
select ops.Opsaetning as opsaetning, A.EditionID as editionID, b.FilStr as size, v.Navn as CompanyName, v.CVR as cvr, v.Postnr as postcode, A.AftaleNr, BMA.Tilmeldt as ActivationT, BMA.Frameldes as DeactivationT
from BilagsAttachment as b 
inner join Opsaetning as ops on b.Opsaetning = ops.Opsaetning 
inner join Virksomhed as v on v.Aftalenr = ops.Aftalenr 
inner join Aftalenr as A on A.AftaleNr = v.Aftalenr 
inner join BenyttetModulAftalenr as BMA on BMA.Aftalenr = ops.Aftalenr

where ISNULL(v.SkalFaktureres, 0) = 1 
AND ISNULL(v.ProeveVirksomhed, 0) = 0 
AND A.Spaerret = 0 
AND (A.FrameldingsDato IS NULL 
OR A.FrameldingsDato > GETDATE()) 
AND v.TilSletning = 0 
AND V.Email 
) 
4

2 に答える 2

2

これは SQL サーバーのように見えます。その場合...

select * from
(
    select *, 
        row_number() over 
        (
            partition by [user]
            order by datediff(d,isnull(deactivation, getdate()), activation) desc
        ) as rn
    from yourtable
) v
where rn = 1
于 2012-10-01T08:46:38.020 に答える
1

これを試して:

;WITH DiffCTE
AS
(
    SELECT *, 
     datediff(d,isnull(deactivation, getdate()), activation) 
      AS Time_Difference
    FROM TableName
), MaxDiffs
AS
(
    SELECT t1.*
    FROM DiffCTE t1
    INNER JOIN
    (
      SELECT user, MAX(Time_Difference) MAXTime_Difference
      FROM DiffCTE 
      GROUP BY user
    ) t2 ON t2.user = t2.user AND t1. Time_Difference = t2.MAXTime_Difference
)
SELECT user, activation, Deactivation, usage, dmb
FROM MaxDiffs;

または:ランキング関数を使用すると、次のことができます。

;WITH cte
AS
(
    SELECT *, ROW_NUMBER() OVER(Partition by [user] ORDER BY datediff(d,isnull(deactivation, getdate()), activation) DESC) row_num
    FROM @t
)
SELECT * FROM cte WHERE row_num = 1;

ライブデモはこちら

于 2012-10-01T08:47:17.367 に答える