Pretty much it is easier to show, than to explain:
I have the following table:
The idea is, that I need only the "Objekts", for which I have entered the Datum within the same month. Eg, "aaa" is needed, because I have data for August twice. "bbb" is not needed, because I have once for August and once for Septermber, which is OK.
This is what I've tried so far:
SELECT objekt,count(*) as counter
FROM tempt_report
GROUP BY objekt
HAVING count(*)>1
But obviously, I do not mention the requirement for the "Datum", and thus I do not get what I want.
Thanks! :)
not sure if I'm missing something! You want >1 of any type in a month of a year
SELECT objekt,year(datum),month(datum),count(*) as counter
FROM tempt_report
GROUP BY objekt, year(datum),month(datum)
HAVING count(*)>1
SELECT objekt,dateadd(month,DATEDIFF(MONTH, 0, datum),0) m
FROM tempt_report
GROUP BY objekt,DATEDIFF(MONTH, 0, datum)
HAVING count(*)>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
You can try this query?
You might try this like this:
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
Since you are using SQL Server 2014 you can use 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.