【问题标题】:Sql rows count with groupingSql 行计数与分组
【发布时间】:2017-06-11 21:12:34
【问题描述】:

您好,我有两张表如下

tblContactType

typeId  typeName active
1       Email      1
2       Phone      1
3       Address    1
4       Fax        1

tblContact

id    IdName   typeId  groupId
100    test      1       1
101    test2     1       1
102    test3     1       2
103    test4     2       2
104    test5     2       3
105    test6     3       3

希望结果以列名作为 typeName 计数并按组 ID 分组。结果应该是与组关联的类型总数,这些类型与联系人关联。

GroupId    EmailCount    PhoneCount  AddressCount     FaxCount
1           2             0             0               0
2           1             1             0               0
3           0             1             1               0  

【问题讨论】:

  • 到目前为止您尝试过什么?您可以通过 LEFT JOIN、GROUP BY、SUM 和 IIF 或 CASE 来实现这一点
  • 你知道数据透视查询吗?

标签: sql-server tsql


【解决方案1】:

您可以按如下方式分组和旋转:

Select * from (
    Select t.groupid, tct.typename, t.id from tblContact t 
    inner join tblContactType tct 
    on t.typeid = tct.typeid
) a
pivot (count(a.id) for typename in ([Email],[Phone],[Address],[Fax]) ) p

对于动态列列表,您可以使用如下动态查询:

declare @cols1 varchar(max)
declare @query nvarchar(max)

Select  @cols1 = stuff((Select distinct ','+QuoteName(typename) from tblContactType for xml path('')),1,1,'')
Set     @query = '  Select * from (
        Select t.groupid, tct.typename, t.id from tblContact t 
        inner join tblContactType tct 
        on t.typeid = tct.typeid
    ) a
    pivot (count(a.id) for typename in (' + @cols1 + ') ) p '

Select @query --Check the generated query is good and then execute below
--exec sp_executesql @query

输出如下:

+---------+---------+-------+-----+-------+
| groupid | Address | Email | Fax | Phone |
+---------+---------+-------+-----+-------+
|       1 |       0 |     2 |   0 |     0 |
|       2 |       0 |     1 |   0 |     1 |
|       3 |       1 |     0 |   0 |     1 |
+---------+---------+-------+-----+-------+

【讨论】:

  • 这很好用谢谢。另外,如何添加总列并显示该列中每一行的总和??
【解决方案2】:

这是另一种解决方案。

SELECT groupId,
        SUM(CASE WHEN c.typeId = 1 THEN 1 ELSE 0 END) 'EmailCount',
        SUM(CASE WHEN c.typeId = 2 THEN 1 ELSE 0 END) 'PhoneCount',
        SUM(CASE WHEN c.typeId = 3 THEN 1 ELSE 0 END) 'AddressCount',
        SUM(CASE WHEN c.typeId = 4 THEN 1 ELSE 0 END) 'FaxCount'
FROM tblContact c
    JOIN tblContactType ct ON c.typeId = ct.typeId  
GROUP BY groupId 

结果

-------------------------------------------------------------
groupId  |  EmailCount | PhoneCount | AddressCount | FaxCount
-------------------------------------------------------------
  1      |     2       |    0       |      0       |    0
  2      |     1       |    1       |      0       |    0
  3      |     0       |    1       |      1       |    0
-------------------------------------------------------------

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多