0

我们有 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 查询会提前谢谢

问候莫克沙

4

3 回答 3

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
于 2012-05-07T12:32:37.657 回答
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]

SQL Fiddle 示例

于 2012-05-07T13:50:38.900 回答
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"),
            };
于 2012-05-07T13:47:22.030 回答