实体框架交叉列分组依据

问题描述

我有一张狗和品种表,每个品种名称都有3种气质,如下所示:

    NAME    |    TEMP1    |    TEMP2    |    TEMP3
------------+-------------+-------------+------------
   Check1   |   angry     |     Shy     |    Ugly
   Check2   |   Rude      |    Cute     |    Shy
   Check3   |    Bla      |    angry    |    Smelly

我想要一个结果,它穿过气质列并将其分组为:

  Temp   |   COUNT(*)
---------+------------
 Shy     |      2
angry    |      2
.
.
.

如果可能的话,您可以使用Entity Framework回答这篇文章(如果不是,可以用sql编写,我会(如果可能)将其转换为Entity Framework)就很好了。

非常感谢!

解决方法

在支持横向联接的SQL数据库(例如SQL Server,Postgres或Oracle)中,通常不需使用横向联接,然后进行聚合:

select x.tmp,count(*) cnt
from mytable t
cross apply (values (temp1),(temp2),(temp3)) x(tmp)
group by x.tmp

在Postgres中,语法为cross join lateral,而不是cross apply

在其他数据库中,您可以使用union all取消透视(效率较低,因为它需要进行多个表扫描):

select x.tmp,count(*) cnt
from (
    select temp1 tmp from mytable
    union all select temp2 from mytable
    union all select temp2 from mytable
) x
group by x.tmp