我如何编写导致以下内容的查询...
假设我的数据集看起来像这样:
| PersonId | LastName | FirstName | ProductType | ProductValue |
|----------|----------|-----------|-------------|--------------|
| P0000001 | Bloggs | Joe | 1 | £15 |
| P0000001 | Bloggs | Joe | 1 | £20 |
| P0000001 | Bloggs | Joe | 2 | £10 |
| P0000001 | Bloggs | Joe | 3 | £5 |
| P0000002 | Doe | Jane | 2 | £25 |
| P0000002 | Doe | Jane | 3 | £60 |
| P0000003 | Brown | Jim | 1 | £20 |
| P0000003 | Brown | Jim | 3 | £5 |
如果PersonId
在ProductType = 1
个记录集中至少有1次出现PersonId
,则返回该PersonId
的所有记录(即使从集合返回的其他记录的ProductType
不是1)。
所以上面的数据集会像这样过滤:
| PersonId | LastName | FirstName | ProductType | ProductValue |
|----------|----------|-----------|-------------|--------------|
| P0000001 | Bloggs | Joe | 1 | £15 |
| P0000001 | Bloggs | Joe | 1 | £20 |
| P0000001 | Bloggs | Joe | 2 | £10 |
| P0000001 | Bloggs | Joe | 3 | £5 |
| P0000003 | Brown | Jim | 1 | £20 |
| P0000003 | Brown | Jim | 3 | £5 |
Jane Doe没有ProductType = 1
的任何记录,所以她的所有记录都被过滤掉了。 Joe Bloggs和Jim Brown在ProductType = 1
中至少有1条记录,因此在查询中返回了所有的记录。
答案 0 :(得分:2)
您可以使用GROUP BY和HAVING子句:
SELECT PersonID, LastName, Firstname
FROM tbl
WHERE ProductType=1
GROUP BY PersonID, LastName, FirstName
HAVING COUNT(*) >=1
然后你使用IN子句:
SELECT * FROM tbl
WHERE PersonID IN (
SELECT PersonID
FROM tbl
WHERE ProductType=1
GROUP BY PersonID
HAVING COUNT(*) >=1
)
答案 1 :(得分:2)
您可以使用EXISTS
执行此操作。像这样:
SELECT
*
FROM
yourTable as tbl
WHERE EXISTS
(
SELECT
NULL
FROM
yourTable AS tbl1
WHERE
yourTable.PersonId=tbl.PersonId
AND tbl1.ProductType=1
)
这将为您提供输出:
P0000001 Bloggs Joe 1 £15
P0000001 Bloggs Joe 1 £20
P0000001 Bloggs Joe 2 £10
P0000001 Bloggs Joe 3 £5
P0000003 Brown Jim 1 £20
P0000003 Brown Jim 3 £5