可以在TSQL中执行SUM IF等效,其中条件不是常数吗?

时间:2017-05-25 20:27:56

标签: sql-server tsql aggregate ssms

我有可用于许可证的数据和每10分钟可用的最大许可证数据,我希望按天汇总,并且需要知道每天的许可证最大数量(使用的许可证=总许可证数)。我已经看到很多条件,其中列等于常量,但是对于一列等于另一列的条件,我找不到任何条件。我无法对最大许可证进行硬编码,因为这需要适用于数千种不同的软件包,理论上相同的软件包在给定时间段内可能拥有不同数量的最大许可证。请帮忙!

到目前为止,我知道SELECT语句中的第3行是错误的,但不知道要使用什么。

DECLARE @unixTimeStamp INT = 1495571176;
DECLARE @featValue INT = 877;
DECLARE @unixMark INT = @unixTimeStamp - 2629746;

SELECT 
    FORMAT(DATEADD(S, StampedUnixTime, '1970-01-01'), 'MM/dd') AS Date
    COUNT(*) FILTER WHERE UsedLicenses = TotalLicenses AS Maxouts,
    MAX(FH.UsedLicenses) AS UsedLicenses, 
    MAX(FH.TotalLicenses) AS TotalLicenses
FROM Feature_History as FH 
WHERE ([FeatureID] = @featValue) AND (FH.StampedUnixTime BETWEEN @unixMark AND @unixTimeStamp)
GROUP BY FORMAT(DATEADD(S, StampedUnixTime, '1970-01-01'), 'MM/dd')
ORDER BY Date

1 个答案:

答案 0 :(得分:0)

我认为您需要的只是条件聚合。

DECLARE @unixTimeStamp INT = 1495571176;
DECLARE @featValue INT = 877;
DECLARE @unixMark INT = @unixTimeStamp - 2629746;

SELECT 
    FORMAT(DATEADD(S, StampedUnixTime, '1970-01-01'), 'MM/dd') AS Date,
    sum(case when UsedLicenses = TotalLicenses then 1 else 0 end) as MaxOuts,
    MAX(FH.UsedLicenses) AS UsedLicenses, 
    MAX(FH.TotalLicenses) AS TotalLicenses
FROM Feature_History as FH 
WHERE ([FeatureID] = @featValue) AND (FH.StampedUnixTime BETWEEN @unixMark AND @unixTimeStamp)
GROUP BY FORMAT(DATEADD(S, StampedUnixTime, '1970-01-01'), 'MM/dd')
ORDER BY Date