Sql 需要获取过去3天使用的物品数量以及去年使用的物品数量
我有一个查询,在那里我可以完美地获取最近3天的记录Sql 需要获取过去3天使用的物品数量以及去年使用的物品数量,sql,Sql,我有一个查询,在那里我可以完美地获取最近3天的记录 Select ProductID, Description, Count(productID) AS [Last 3 days item count] From VIEW_ItemsUsed Where DateUsed >= Getdate()-3 Group by ProductID 但是当我在同一个查询中包含获取去年使用的项数的条件时,会获取无效数据 Select ProductID, Description, Count(
Select ProductID, Description, Count(productID) AS [Last 3 days item count]
From VIEW_ItemsUsed
Where DateUsed >= Getdate()-3
Group by ProductID
但是当我在同一个查询中包含获取去年使用的项数的条件时,会获取无效数据
Select ProductID, Description, Count(productID) AS [Last 3 days item count], Count(ProductID) AS [Last Year Item counts]
From VIEW_ItemsUsed
Where DateUsed >= Getdate()-3
AND DateUsed >= Getdate()-365
Group by ProductID
请为我提供解决方案我认为您只需要条件聚合:
Select ProductID, Description,
sum(case when dateUsed >= getdate() - 3 then 1 else 0 end) as cnt_3days,
sum(case when dateUsed >= getdate() - 365 then 1 else 0 end) as cnt_365days
From VIEW_ItemsUsed
Where DateUsed >= Getdate() - 365
Group by ProductID, Description;
您使用的是哪种DBMS产品?“SQL”只是所有关系数据库使用的查询语言,而不是特定数据库产品的名称(日期/时间函数非常特定于供应商)。请为您正在使用的数据库产品添加。由于您实际在何处过滤数据,因此为了实现此功能,您必须将两个查询与两个WHERE语句组合在一起,一个查询持续3天,另一个查询持续1年。