我有一个名为DataFile
的表。这将保留我每天存储的所有数据记录。
此表中的数据如下所示:
Id ConfigAccountId Shelf FileIdentifier Created
5356341 23 BSAS020006 C200094 28/01/2013
5356342 23 BSAS020006 C200095 28/01/2013
5356343 23 BSAS020006 C200096 28/01/2013
5356344 23 BSAS020006 C200097 28/01/2013
5356345 23 BSAS020006 C200098 28/01/2013
5356346 23 BSAS020006 C200099 28/01/2013
5356347 23 BSAS020006 C200100 28/01/2013
5356348 23 BSAS020006 C200101 28/01/2013
5356349 23 BSAS020006 C200102 28/02/2013
5356350 23 BSAS020006 C200103 28/02/2013
5356351 23 BSAS020006 C200104 28/02/2013
5356352 23 BSAS020006 C200105 28/02/2013
5356353 23 BSAS020006 C200106 28/02/2013
5356354 23 BSAS020006 C200107 28/02/2013
5356355 23 BSAS020007 C200108 28/02/2013
5356356 23 BSAS020007 C200109 28/02/2013
如果你查看数据,shelf
列只有在满时才会更改数字,但是我需要知道我有多少个唯一的 shelf
代码月。问题是 shelf
BSAS020006
运行了超过两个月的时间,因此如果我在 February
运行一个不同的值,它将计入 shelf
> 再次BSAS020006
(我希望我说得有道理)。我每个月都需要一个唯一的货架
计数。因此,如果货架
编号已在一月
报告,并且持续到二月
,则必须仅显示的计数一月
.
这是我到目前为止的代码:
select distinct Shelf
from DataFile
where Created Between convert(datetime, '2015-10-01 00:00:01', 102) and
convert(Datetime, '2015-10-31 23:59:59', 102)
我的输出必须显示,但请注意,架子可以延续到新的月份,因此也不得在该月份显示。
Month Shelf Count
January 15
February 16
March 10
最佳答案
如果我正确理解你的问题,我认为在计数之前使用 unique 和 min 的组合会对你有用:
SELECT COUNT(Shelf) AS UniqueCodesForShelf, FirstMonthForShelf AS Month
FROM
(
SELECT Shelf, MIN(AllMonthsForShelf) AS FirstMonthForShelf
FROM
(
SELECT DISTINCT
Shelf,
DATEADD(m, DATEDIFF(m, 0, Created), 0) AS AllMonthsForShelf
FROM DataFile
) AS T1
GROUP BY Shelf
) AS T2
GROUP BY FirstMonthForShelf
“月份”列的输出是该月第一天的日期。
关于sql - 查找一个月内的不同记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33624817/