从表中选择所有数据,但加入了数场为特定的列值 [英] SELECT all data from a table but adding a count field for a particular column value

查看:136
本文介绍了从表中选择所有数据,但加入了数场为特定的列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想 SELECT 从特定表中的数据通过添加 countField 的结果才是最重要的那相应的次数 Item.ResourceId 存在于所有的结果。

I want to SELECT all the data from a particular table by adding a countField to the results that counts the number of times that the corresponding Item.ResourceId exists in all the results.

SELECT Name, ResourceId, (SELECT COUNT(ResourceId) FROM Item GROUP BY ResourceId) AS foo
FROM Item

这是如何做到这一点?

推荐答案

如果这是你想要的查询

SELECT Name, ResourceId, COUNT(*) FROM Item GROUP BY Name, ResourceId;



将其转换为LINQ如下:

it translates to LINQ as follows.

var result = items.GroupBy(item => new { item.Name, item.ResourceId })
                  .Select(group => new { group.Key.Name, group.Key.ResourceId, Count = group.Count() })
                  .ToList();

或你想要这个查询?

SELECT Name,
       ResourceId,
       (SELECT COUNT(*) FROM Item y WHERE y.ResourceId = x.ResourceId)
FROM
       Item x;

这转化为下面的LINQ表达式。

This translates to the following LINQ expression.

var result = items.Select(item => new
             {
                 item.Name,
                 item.ResourceId,
                 Count = items.Count(x => x.ResourceId == item.ResourceId)
             }).ToList();



由于以下输入

Given the following input

Name   ResourceId
-----------------
 A      1
 A      1
 B      1
 B      2
 B      2
 C      3

第一次查询的产量

Name   ResourceId   Count
-------------------------
 A      1            2
 B      1            1
 B      2            2
 C      3            1

而第二个查询得到这一点。

while the second query yields this.

Name   ResourceId   Count
-------------------------
 A      1            3
 A      1            3
 B      1            3
 B      2            2
 B      2            2
 C      3            1

这篇关于从表中选择所有数据,但加入了数场为特定的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆