简体   繁体   English

SQL一表聚合

[英]SQL one table aggregation

For the last few days I have been attempting to find a method to pull a very important set of information from a table that contains what I call daily counts. 在过去的几天里,我一直在尝试寻找一种方法来从包含我所谓的每日计数的表中提取一组非常重要的信息。 I have a table that is setup as follows. 我有一个表,其设置如下。

person|company|prod1|prod2|prod3|gen_date

Each company has more than one person, and each person can have different combinations of products that they have purchased. 每个公司都有一个以上的人员,并且每个人可以拥有自己购买的产品的不同组合。 What I have been trying to figure out is a SQL statement that will list the number of people that have bought a particular product per company. 我一直试图找出的是一条SQL语句,该语句将列出每个公司购买特定产品的人数。 So an output similar to this: 因此,输出类似于以下内容:

Comp ABC | 13 Prod1 |  3 Prod2 | 5 Prod 3
Comp DEF |  2 Prod1 | 15 Prod2 | 0 Prod 3
Comp HIJ |  0 Prod1 |  0 Prod2 | 7 Prod 3 

Currently if a person did not select a product the value being stored is NULL . 当前,如果某人未选择产品,则存储的值为NULL

Best I have right now is 3 different statements that can produce this information if run on their own. 现在最好的是,如果单独运行3条不同的语句,它们可以产生此信息。

SELECT Count(person) as puchases, company 
FROM Sales  WHERE prod1 = '1' and gendate = '3/24/2010' 
Group BY company
SELECT      company,
            SUM(COALESCE(prod1, 0)) AS total_prod1,
            SUM(COALESCE(prod2, 0)) AS total_prod2,
            SUM(COALESCE(prod3, 0)) AS total_prod3
FROM        Sales  
WHERE       gendate = '2010-03-24' 
GROUP BY    company

But you definitely should normalize you table - split it in 4: 但您绝对应该对表格进行归一化-将其拆分为4:

  • Company, 公司,
  • Person, 人,
  • Product, 产品,
  • Person_Product_Purchase (with the date of the purchase). Person_Product_Purchase(带有购买日期)。

If you just want to check whether the value is in any of the product fields then that is simply done with an OR operator: 如果您只想检查该值是否在任何产品字段中,则只需使用OR运算符即可:

SELECT company, COUNT(person) as purchases
FROM Sales
WHERE (prod1 = '1' OR prod2 = '1' OR prod3 = '1')
AND gendate = '3/24/2010'
GROUP BY company

This won't perform very well, however, and you'll have a hard time getting it to perform well, because your schema hasn't been normalized properly. 但是,这将不能很好地执行,并且您将很难使其良好执行,因为您的架构尚未正确规范化。 If you can, you should fix it to something like this: 如果可以,则应将其修复为以下内容:

Person (PersonID, CompanyID)
Sales (PurchaseID, PersonID, ProductID, GenDate)

Then this query (and many other queries) will be a lot easier to write: 然后,此查询(以及许多其他查询)将更容易编写:

SELECT p.CompanyID, COUNT(*) AS purchases
FROM Person p
INNER JOIN Sales s
    ON s.PersonID = p.PersonID
WHERE s.ProductID = 1
AND s.GenDate = '20100324'
GROUP BY p.CompanyID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM