搜索具有相同日期的记录

时间:2017-07-07 09:24:23

标签: sql sql-server-2008 tsql

从同一个表中确定具有相同日期的记录的最佳方法是什么。

我的分期付款表中有两行:

ORDER_1  | 13 | Paid | 2017-02-01 00:00:00.000 |
ORDER_2  | 14 | Paid | 2017-02-01 00:00:00.000 |

我需要能够显示日期相同的所有分期付款。

我试过了:

SELECT *  FROM ORDER_INSTALMENT WHERE DATEDUE = DATEDUE

2 个答案:

答案 0 :(得分:1)

SELECT a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
FROM ORDER_INSTALMENT AS a INNER JOIN ORDER_INSTALMENT AS b
ON a.DATEDUE = b.DATEDUE  
AND a.OrderID <> b.OrderID
GROUP BY a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
ORDER BY a.DATEDUE

如果在表格中使用索引,即使结果和速度相同,也可以使用distinct来简化:

SELECT DISTINCT a.OrderID, a.InstalmentID, a.InstalmentSatus, a.DateDue
FROM ORDER_INSTALMENT AS a INNER JOIN ORDER_INSTALMENT AS b
ON a.DATEDUE = b.DATEDUE  
AND a.OrderID <> b.OrderID
ORDER BY a.DATEDUE

答案 1 :(得分:1)

您可以使用exists或内部联接:

SELECT *
FROM ORDER_INSTALMENT o
WHERE EXISTS
(
    SELECT 1
    FROM ORDER_INSTALMENT i
    WHERE o.DATEDUE = i.DATEDUE
    AND i.<UniqueColumnName> <> o.<UniqueColumnName>
)

SELECT DISTINCT t1.*
FROM ORDER_INSTALMENT t1
INNER JOIN ORDER_INSTALMENT t2
ON t1.DATEDUE = t2.DATEDUE
AND t1.<UniqueColumnName> <> t2.<UniqueColumnName>

请注意,您需要将<UniqueColumnName>更改为表格中唯一的列名。

另一种选择:

;WITH CTE AS
(
    SELECT DATEDUE, COUNT(*) As NumberOfRows
    FROM ORDER_INSTALMENT 
    GROUP BY DATEDUE
)
SELECT *
FROM ORDER_INSTALMENT t
INNER JOIN CTE
ON t.DATEDUE = CTE.DATEDUE
WHERE NumberOfRows > 1