计算sql server表中的元素数

时间:2011-05-01 09:31:45

标签: asp.net sql-server sql-server-2005 linq-to-sql

我有两张表,如下所示:

文章表:

,输出应如下所示:

enter image description here

如何使用sql查询(我使用sql server 2005)和使用linq进行sql查询来实现这一目标?

BTW我在Visual Studio 2008中使用sql server 2005,带有c#的asp.net。

请帮帮我

感谢您的期待

3 个答案:

答案 0 :(得分:2)

select 
  A.SNo,
  A.Article_Name,
  count(C.Article_Name) as Total_Items_Bought
from Articles as A
  left outer join CustomersRecord as C
    on A.Article_Name = C.Article_Name
group by A.SNo, A.Article_Name    
order by A.SNo

答案 1 :(得分:2)

更新:添加了Linq experssion,可以在需要OUTER加入时使用。


INNER JOIN

对于内部联接即。只收回至少购买过一次的文章,你可以使用以下内容。

LINQ 2 SQL

from a in Articles
join c in CustomersRecords on 
     a.Article_Name equals c.Article_Name 
group a by new {a.SNo, a.Article_Name} into g
select new 
       {
         SNo = g.Key.SNo, 
         Article_Name = g.Key.Article_Name, 
         Total_Items_Bought = g.Count()
       }

以上转换为以下SQL

SELECT COUNT(*) AS [Total_Items_Bought], [t0].[SNo], [t0].[Article_Name]
FROM [Articles] AS [t0]
INNER JOIN [CustomersRecord] AS [t1] ON [t0].[Article_Name] = [t1].[Article_Name]
GROUP BY [t0].[SNo], [t0].[Article_Name]

当清理一下时会给你

SELECT a.SNo, 
       a.Article_Name, 
       COUNT(*) AS Total_Items_Bought
  FROM Articles AS a
 INNER JOIN CustomersRecord AS c ON a.Article_Name = c.Article_Name
 GROUP BY a.SNo, a.Article_Name

LEFT OUTER JOIN

对于左外连接即。回到所有从未购买过的文章活动,您可以使用以下内容。

LINQ 2 SQL

from a in Articles
join c in CustomersRecords on 
     a.Article_Name equals c.Article_Name into apc
select new 
       {
         SNo = a.SNo, 
         Article_Name = a.Article_Name, 
         Total_Items_Bought = apc.Count()
       }

这转换为以下SQL

 SELECT [t0].[SNo], [t0].[Article_Name], (
    SELECT COUNT(*)
    FROM [CustomersRecord] AS [t1]
    WHERE [t0].[Article_Name] = [t1].[Article_Name]
    ) AS [Total_Items_Bought]
 FROM [Articles] AS [t0]

答案 2 :(得分:1)

将此用于SQL

SELECT 
   SNO,Article_Name, 
   (SELECT COUNT(*) FROM CustomersRecord AS cr 
    WHERE cr.Article_Name = Article_Name) AS Total_Items_Bought 
FROM ARTICLES