2015-04-17 188 views
1

如何從Microsoft SQL Server表中刪除所有重複的月份?刪除重複行查詢結果(Microsoft SQL Server中除外)?

例如,下面的語法我剛剛創建:

SELECT * FROM Cash WHERE Id = '2' AND TransactionDate between '2014/07/01' AND '2015/02/28' 

,查詢結果是:

+----+-------------------------+ 
|Id | TransactionDate   | 
+----+-------------------------+ 
| 2 | 2014-07-22 00:00:00.000 | 
| 2 | 2014-08-09 00:00:00.000 | 
| 2 | 2014-08-25 00:00:00.000 | 
| 2 | 2014-08-29 00:00:00.000 | 
| 2 | 2015-01-27 00:00:00.000 | 
| 2 | 2015-01-28 00:00:00.000 | 
+----+-------------------------+ 

我將如何刪除重複一個月了僅針對任何返回任何值1每個月1個月,如下所示:

+----+-------------------------+ 
|Id | TransactionDate   | 
+----+-------------------------+ 
| 2 | 2014-07-22 00:00:00.000 | 
| 2 | 2014-08-09 00:00:00.000 | 
| 2 | 2015-01-27 00:00:00.000 | 
+----+-------------------------+ 
+0

你想刪除或只是不選擇它們? – mxix

+0

只是沒有選擇它們,所以不會有重複月份的查詢結果。 – user2731263

回答

0

每月只選第一行

SELECT * 
FROM Cash c 
WHERE c.Id = '2' 
AND c.TransactionDate between '2014/07/01' AND '2015/02/28' 
AND NOT EXISTS (SELECT 'a' 
        FROM Cash c2 
        WHERE c2.Id = c.Id 
        AND YEAR(c2.TransactionDate) * 100 + MONTH(c2.TransactionDate) = YEAR(c.TransactionDate) * 100 + MONTH(c.TransactionDate) 
        AND c2.TransactionDate < c.TransactionDate 
       ) 
2

您可以在ROW_NUMBER的幫助下完成。

這會告訴你哪些是你要保持

SELECT id,transactionDate, ROW_NUMBER() OVER (PARTITION BY YEAR(TransactionDate),MONTH(TransactionDate) ORDER BY TransactionDate) firstTrans 
FROM Cash 
WHERE Id = '2' AND 
TransactionDate between '2014/07/01' AND '2015/02/28' 

您可以刪除與CTE其他行的行。

with myCTE (id,transactionDate, firstTrans) AS (
SELECT id,transactionDate, ROW_NUMBER() OVER (PARTITION BY YEAR(TransactionDate),MONTH(TransactionDate) ORDER BY TransactionDate) firstTrans 
    FROM Cash 
    WHERE Id = '2' AND 
    TransactionDate between '2014/07/01' AND '2015/02/28' 
) 
delete from myCTE where firstTrans <> 1 

每個月每個月只會保留一筆交易。

編輯:

由ROW_NUMBER過濾器將只返回行你想

select id, transactionDate from (SELECT id,transactionDate, ROW_NUMBER() OVER (PARTITION BY YEAR(TransactionDate),MONTH(TransactionDate) ORDER BY TransactionDate) firstTrans 
    FROM Cash 
    WHERE Id = '2' AND 
    TransactionDate between '2014/07/01' AND '2015/02/28') where firstTrans = 1 
0

當您運行此查詢,您將得到最高的ID爲每年每個月。

SELECT MAX(<IdColumn>) AS Id, YEAR(<DateColumn>) AS YE, MONTH(<DateColumn>) AS MO FROM <YourTable> 
GROUP BY YEAR(<DateColumn>), MONTH(<DateColumn>) 

如果需要的話,例如,你可以晚刪除行,他們的ID沒有在此查詢。