Multiple criteria in 1 query

后端 未结 1 1259
生来不讨喜
生来不讨喜 2021-01-27 02:09

I have one table of peoples names and I have another table of pledges these people have made.

They might pledge money against item 1,2,3 or 4.

Each time a pledge

相关标签:
1条回答
  • 2021-01-27 02:48

    You could try this using the EXISTS

    SELECT     COUNT(DISTINCT PersonID) DistinctCountPersons
    FROM       pledges p
    WHERE     EXISTS(SELECT * FROM pledges WHERE PersonID = p.PersonID AND ItemID = 1)
    AND     EXISTS(SELECT * FROM pledges WHERE PersonID = p.PersonID AND ItemID = 2)
    

    EDIT

    Regarding the second part of the query, you can try

    SELECT  p.PersonID,
            pp.PersonName,
            SUM(p.Pledge) TotalPledged
    FROM    pledges p INNER JOIN
            people pp ON p.PersonID = pp.PersonID
    WHERE   EXISTS(SELECT * FROM pledges WHERE PersonID = p.PersonID AND ItemID = 1)
    AND     EXISTS(SELECT * FROM pledges WHERE PersonID = p.PersonID AND ItemID = 2)
    GROUP BY p.PersonID,pp.PersonName
    
    0 讨论(0)
提交回复
热议问题