我有一个C#应用程序,可以显示公司销售的产品。该列的旁边是产品类型,最后一列是购买该产品的客户数量。这是我的SQL查询,用于填充前两列:
string selectQuery;
selectQuery = "SELECT Products.ProductID, Products.ProductTypeID, ";
selectQuery = selectQuery + "Products.ProductName, Products.YearlyPremium, ProductTypes.ProductType ";
selectQuery = selectQuery + "FROM Products ";
selectQuery = selectQuery + "INNER JOIN ProductTypes ON Products.ProductTypeID = ProductTypes.ProductTypeID "
现在,我需要计算出有多少客户购买了每种产品。我想我需要使用COUNT(*)
方法来获取CustomerID,但现在确定如何将其集成到此查询中。
这是架构
我用于在listView中显示数据的代码是这样的:
SqlConnection conn = ConnectionsManager.DatabaseConnection();
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(selectQuery, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Products product = new Products(int.Parse(rdr["ProductID"].ToString()),
int.Parse(rdr["ProductTypeID"].ToString()),
rdr["ProductName"].ToString(),
Math.Round(decimal.Parse(rdr["YearlyPremium"].ToString()), 2));
ProductTypes productType = new ProductTypes(int.Parse(rdr["ProductTypeID"].ToString()),
rdr["ProductType"].ToString());
ListViewItem lvi = new ListViewItem(product.ProductName.ToString());
lvi.SubItems.Add(productType.ProductType.ToString());
\\lvi.SubItems.Add(customer.CustomerID.ToString()); <---this will be the line to display the customer count
lvMain.Items.Add(lvi);
}
if (rdr != null)
rdr.Close();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unsuccessful" + ex);
}
答案 0 :(得分:0)
考虑到ProductTypeId在最终结果中必须为NON NULL值(因此使用INNER JOIN),这是您必须在C#代码中嵌入的SQL部分:
SELECT P.ProductID, P.ProductTypeID, P.ProductName, P.YearlyPremium, PT.ProductType, CustomerCount = COUNT(S.CustomerID)
FROM Sales S
INNER JOIN Products P
ON S.ProductID = P.ProductID
INNER JOIN ProductTypes PT
ON P.ProductTypeID = PT.ProductTypeID
GROUP BY P.ProductID, P.ProductTypeID, P.ProductName, P.YearlyPremium, PT.ProductType
注意:-由于不需要客户的任何属性,并且您在Sales.CustomerID列上具有Customer.CustomerId列的外键,因此,为了获取CustomerCount,不必加入Customer表
答案 1 :(得分:0)
尝试使用Group by子句。它会工作。 示例:
SELECT COUNT(ProductId),CustomerId
FROM Product
GROUP BY CustomerId;
这种
答案 2 :(得分:0)
您似乎想要一个基本的GROUP BY
查询:
SELECT p.ProductID, p.ProductTypeID, p.ProductName, p.YearlyPremium,
pt.ProductType,
COUNT(DISTINCT s.CustomerID) as num_customers
FROM Products p INNER JOIN
ProductTypes pt
ON p.ProductTypeID = PT.ProductTypeID LEFT JOIN
Sales S
ON s.ProductID = p.ProductID
GROUP BY p.ProductID, p.ProductTypeID, p.ProductName, p.YearlyPremium, pt.ProductType;
注意:
LEFT JOIN
至Sales
来获得没有销售的产品。INNER JOIN
到ProductTypes
,因为大概所有产品都具有类型。GROUP BY
具有所有未汇总的列。Sales
中的记录,请删除DISTINCT
。