假设我有一张桌子SALES
Date ArticleID CustomerID SalesID
2016-04-01 4 1000 1
2016-04-01 8 1000 2
2016-04-01 4 1000 3
2016-04-01 12 1000 4
2016-04-02 4 1000 5
2016-04-03 6 800 6
2016-04-03 4 1000 7
2016-04-05 99 900 8
2016-04-06 4 700 9
我的目标是创建一个查询,该查询仅返回同一客户在同一天购买相同文章的行。
在这种情况下,结果应为:
Date ArticleID CustomerID SalesID
2016-04-01 4 1000 1
2016-04-01 4 1000 3
如何以最佳方式编写此查询?谢谢你的帮助!
答案 0 :(得分:3)
您可以使用GROUP BY
和HAVING
:
SELECT t.*
FROM tbl t
INNER JOIN (
SELECT CustomerID, Date, ArticleID
FROM tbl
GROUP BY CustomerID, Date, ArticleID
HAVING COUNT(SalesID) >= 2
)a
ON a.CustomerID = t.CustomerID
AND a.Date = t.Date
AND a.ArticleID = t.ArticleID
另一种方法是使用COUNT OVER
:
WITH Cte AS(
SELECT *,
cnt = COUNT(SalesID) OVER(PARTITION BY CustomerID, Date, ArticleID)
FROM tbl
)
SELECT
Date, ArticleID, CustomerID, SalesID
FROM Cte
WHERE cnt >= 2
答案 1 :(得分:1)
一种方法是使用CTE group by和having,然后加入原始表:
;WITH CTE AS
(
SELECT Date, ArticleId, CustomerId
FROM Sales
GROUP BY Date, ArticleId, CustomerId
HAVING COUNT(SalesId) > 1
)
SELECT S.Date, S.ArticleId, S.CustomerId, S.SalesId
FROM Sales S
INNER JOIN CTE C ON(S.Date = C.Date AND S.ArticleId = C.ArticleId AND S.CustomerId = C.CustomerId)
答案 2 :(得分:1)
请尝试以下查询
select date,articleid,customerid,salesid from sales
inner join
(select date,articleid,customerid
from sales
group by date,articleid,customerid
having count(1)>1) b
on sales.date=b.date
and sales.articleid=b.articleid
and sales.customerid=b.customerid
答案 3 :(得分:1)
使用子查询执行此操作。
SELECT A.*
FROM YourTable AS A INNER JOIN (
SELECT Date, ArticleID, CustomerID, COUNT(*) AS NumberOfCount
FROM YourTable
GROUP BY Date, ArticleID, CustomerID
HAVING COUNT(*) >1 ) AS B
ON A.Date = B.Date
AND A.ArticleID = B.ArticleID
AND A.CustomerID = B.CustomerID
答案 4 :(得分:1)
您可以在COUNT()
中使用OVER
:
select Date_, ArticleID, CustomerId, SalesID
from (select *,
count(*) over(partition by Date_, ArticleID, CustomerId) cnt
from #t )x
where cnt > 1