相比之下,展示更容易,而不是解释:
我有下表:
我的想法是,我只需要“Objekts”,我在同一个月内进入了Datum。 例如,需要“aaa”,因为我有8月两次的数据。不需要“bbb”,因为我曾经八月一次,一次是Septermber,这是好的。
这是我到目前为止所尝试的:
SELECT objekt,count(*) as counter
FROM tempt_report
GROUP BY objekt
HAVING count(*)>1
但显然,我没有提到“基准”的要求,因此我得不到我想要的东西。
谢谢! :)
答案 0 :(得分:2)
不确定我是否遗漏了什么!你想要一年中一个月的任何类型的> 1
SELECT objekt,year(datum),month(datum),count(*) as counter
FROM tempt_report
GROUP BY objekt, year(datum),month(datum)
HAVING count(*)>1
答案 1 :(得分:1)
SELECT objekt,dateadd(month,DATEDIFF(MONTH, 0, datum),0) m
FROM tempt_report
GROUP BY objekt,DATEDIFF(MONTH, 0, datum)
HAVING count(*)>1
答案 2 :(得分:1)
select MONTH(Datum) +' '+ YEAR(Datum) AS Datum,
objekt,
COUNT(1) from #tempt_report
GROUP by objekt,YEAR(Datum), MONTH(Datum)
HAVING count(1) > 1
您可以尝试此查询吗?
答案 3 :(得分:0)
您可以这样尝试:
DECLARE @tbl TABLE(YourDate DATE,YourObjekt VARCHAR(100));
INSERT INTO @tbl VALUES
({d'2016-08-01'},'aaa')
,({d'2016-08-31'},'aaa')
,({d'2016-08-31'},'bbb')
,({d'2016-09-01'},'aaa')
,({d'2016-09-02'},'bbb');
WITH PartitionedCounted AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY YourObjekt,YearAndMonth ORDER BY YourDate) AS Nr
,YearAndMonth
,YourDate
,YourObjekt
FROM @tbl AS tbl
CROSS APPLY(SELECT CONVERT(VARCHAR(7),YourDate,102) AS YearAndMonth) AS A
)
SELECT pc.YearAndMonth,pc.YourObjekt,tbl.YourDate
FROM PartitionedCounted AS pc
INNER JOIN @tbl AS tbl ON tbl.YourObjekt=pc.YourObjekt AND CONVERT(VARCHAR(7),tbl.YourDate,102)=pc.YearAndMonth
WHERE pc.Nr > 1
由于您使用的是SQL Server 2014,因此可以使用EOMONTH
:
WITH PartitionedCounted AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY YourObjekt,EOMONTH(YourDate) ORDER BY YourDate) AS Nr
,EOMONTH(YourDate) AS EOM
,YourDate
,YourObjekt
FROM @tbl AS tbl
)
SELECT pc.EOM,pc.YourObjekt,tbl.YourDate
FROM PartitionedCounted AS pc
INNER JOIN @tbl AS tbl ON tbl.YourObjekt=pc.YourObjekt AND EOMONTH(tbl.YourDate)=pc.EOM
WHERE pc.Nr > 1