2017-06-11 6 views
0
Gruppierung

Hallo Ich habe zwei Tabellen wie untenSql Reihen zählen mit

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 

die Ergebnisse Möchten Sie mit Spaltennamen werden als Typname und von Gruppen-ID gruppiert zu zählen. Die Ergebnisse sollten die Gesamtzahl der einer Gruppe zugeordneten Typen sein, die einem Kontakt zugeordnet sind.

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

was haben Sie bisher versucht? Sie können dies erreichen, indem Sie LINKER JOIN, GROUP BY, SUM und IIF oder CASE – maSTAShuFu

+0

kennen Pivot-Abfrage? –

Antwort

1

Sie können Gruppe durch und schwenken wie folgt:

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 

Für dynamische Liste der Spalten können Sie wie unten dynamische Abfrage verwenden:

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 

Ausgabe wie folgt:

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

Das funktioniert ganz gut, danke. Wie kann ich auch eine Gesamtspalte hinzufügen und die Summe jeder Zeile in dieser Spalte anzeigen? – user3038399

0

ist hier eine andere Lösung.

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 

Ergebnisse

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