按ShopName分组计数不同类型的客户(会员)

时间:2012-05-07 12:24:02

标签: sql-server linq

我们有2张桌子

表1
我们有商店详情的商店

ShopNo, ShopName

表2
客户我们拥有所有客户详细信息

CustomerId, CustomerName, MembershipType, ShopId 

我们要查询的是

ShopName   SilverMember GoldMember LifeMember

ABC        45           110        1

XYZ        90           0          10

DEF        10           10         7

有没有办法让它成为可能

如果在Linq中很好而且只有sql查询会提前感谢

此致 解脱

3 个答案:

答案 0 :(得分:2)

这样的事情可以解决问题:

select s.ShopName,
       count(c1.CustomerId) as 'SilverMember',
       count(c2.CustomerId) as 'GoldMember',
       count(c3.CustomerId) as 'LifeMember'
from Shop s
left outer join Customer c1 on c1.ShopId = s.ShopNo and c1.MembershipType = 'SilverMember'
left outer join Customer c2 on c2.ShopId = s.ShopNo and c2.MembershipType = 'GoldMember'
left outer join Customer c3 on c3.ShopId = s.ShopNo and c3.MembershipType = 'LifeMember'
group by s.ShopName

答案 1 :(得分:1)

假设MembershipType包含实际的VARCHAR值SilverMemberGoldMemberLifeMember,这应该适用于T-SQL:

SELECT
    [ShopName], COUNT([SilverMember]) AS [SilverMember], COUNT([GoldMember]) AS [GoldMember], COUNT([LifeMember]) AS [LifeMember]
FROM
    [Table1]
    INNER JOIN [Table2]
        ON [Table1].[ShopNo] = [Table2].[ShopId]
    PIVOT
    (
        MAX([MembershipType])
            FOR [MembershipType] IN ([SilverMember], [GoldMember], [LifeMember])
    ) AS [P]
GROUP BY
    [ShopName]

Example on SQL Fiddle

答案 2 :(得分:0)

如果你想使用linq:

var query = from s in context.Shops
            join c in context.Customers on s.ShopNo equals c.ShopId
            group c by s.ShopName into g
            select new 
            {
              ShopName = g.Key,
              SilverMember = g.Count(c => c.MembershipType == "SilverMember"),
              GoldMember= g.Count(c => c.MembershipType == "GoldMember"),
              LifeMember= g.Count(c => c.MembershipType == "LifeMember"),
            };