SQL Count Inner Join by Grouping

时间:2012-11-04 19:48:52

标签: sql count group-by inner-join

我搜索了所有的SQL问题,我找到了我不想要的每个版本 - 所以我需要问一下。我处于大脑锁定状态 - 知道有一个计数,总和,小组和一个联合都被扔在一起。

2桌

  1. CustomerTable - CustID,CustQuality(价值观是好客户,坏客户,新客户等)
  2. PurchaseTable(PurchID,PurchItem,PurchDate)
  3. 我正在尝试计算过去30天内Good,Bad,New Customers的购买量。

    我已尝试过加入和小组计数等,我一直在接受:

    • GoodCustomer - CustID2 - 1 purch
    • GoodCustomer - CustID3 - 3 purch
    • GoodCustomer - CustID4 - 2 purch
    • BadCustomer - CustID7 - 2 purch
    • BadCustomer - CustID1 - 4 purch
    • NewCustomer - CustID9 - 1 purch
    • NewCustomer - CustID4 - 4 purch等等。

    我只想要整体结果

    • 3位好客户进行了6次购买
    • 2个坏客户进行了6次购买
    • 2位新客户制作了5个Purcahses

    然后为了额外的功能......我还有第三张桌子,我也需要加入。 CustomerLocation(CLID,CLLocation(北,南,东,西)的值)

    所以,如果我想知道以下细分群体

    • 3位好客户进行了6次购买 - 1位客户来自北方,2位来自南方的客户
    • 2个坏客户进行了6次购买 - 来自East的5位客户,1位West
    • 2位新客户制作了5个Purcahses - 来自South的2位客户

    最后一个新查询将是...... WHERE CLLocation = South

    或者,如果我想按区域查找......

    • 1好客户进行了3次购买
    • 2个坏客户进行了2次购买
    • 0新客户提出0 Purcahses

    我知道我要求很多 - 但是任何和所有帮助都会受到极大的赞赏!

2 个答案:

答案 0 :(得分:0)

这应该回答你的第一个问题

SELECT COUNT(DISTINCT c.CustID), CustQuality, COUNT(PurchID) FROM CustomerTable c
INNER JOIN PurchaseTable p ON c.CustID = p.CustID
GROUP BY CustQuality

答案 1 :(得分:0)

SELECT C.CustQuality, COUNT(DISTINCT c.CustID) AS tot_Customer, COUNT(PurchID) AS tot_Purch
FROM CustomerTable C, PurchaseTable P
WHERE C.CustID = P.PurchCustID
GROUP BY C.CustQuality;

SELECT C.CustQuality, CL.CLocation,  COUNT(DISTINCT c.CustID) AS tot_Customer, COUNT(PurchID) AS tot_Purch
FROM CustomerTable AS C, PurchaseTable AS P, CustomerLocation AS CL
WHERE C.CustID = P.PurchCustID AND CL.LCTCustID = C.CustID
GROUP BY C.CustQuality, CL.CLocation;

SELECT C.CustQuality, CL.CLocation,  COUNT(DISTINCT c.CustID) AS tot_Customer, COUNT(PurchID) AS tot_Purch
FROM CustomerTable AS C, PurchaseTable AS P, CustomerLocation AS CL
WHERE C.CustID = P.PurchCustID AND CL.LCTCustID = C.CustID AND CL.CLocation='North'
GROUP BY C.CustQuality;