1

我在 SQL Server 2012 中有查询以查看我公司的用户部门。

SELECT mdl_user_info_data.data
FROM 
    dbo.mdl_user, 
    dbo.mdl_course, 
    dbo.mdl_user_enrolments, 
    dbo.mdl_enrol, 
    dbo.mdl_course_categories,
    dbo.mdl_user_info_data
WHERE 
    mdl_course.id = mdl_enrol.courseid AND 
    mdl_enrol.id = mdl_user_enrolments.enrolid AND 
    mdl_user_enrolments.userid = mdl_user.id AND 
    mdl_course.category = mdl_course_categories.id AND 
    mdl_course.id = 3 and
    mdl_user_info_data.fieldid = 3 and
    mdl_user.id = mdl_user_info_data.userid

我的查询结果是:

|data|
|CIS|
|CIS|
|TOP|

但我想要的是这样的:

|DATA| TOTAL |
|CIS | 2 |
|TOP | 1 |

有人可以帮助我吗?总之感谢。

我的 mdl_user_info_data 属性:

[id] [bigint] IDENTITY(1,1) NOT NULL,
[userid] [bigint] NOT NULL,
[fieldid] [bigint] NOT NULL,
[data] [ntext] NOT NULL,
[dataformat] [smallint] NOT NULL,

mdl_user_info_data 中的某些行:
id userid fieldid data dataformat
3 3 3 CIS 0

4

2 回答 2

2

试试这个——

SELECT id.data, COUNT(1)
FROM dbo.mdl_user u
JOIN dbo.mdl_user_enrolments ue ON ue.userid = u.id
JOIN dbo.mdl_enrol e ON e.id = ue.enrolid
JOIN dbo.mdl_course c ON c.id = e.courseid
--JOIN dbo.mdl_course_categories cc ON c.category = cc.id
JOIN dbo.mdl_user_info_data id ON u.id = id.userid
WHERE c.id = 3
     AND id.fieldid = 3
GROUP BY id.data

更新:

SELECT t.data, Total = COUNT(1) 
FROM (
     SELECT data = CAST(id.data AS NVARCHAR(MAX))
     FROM dbo.mdl_user u
     JOIN dbo.mdl_user_enrolments ue ON ue.userid = u.id
     JOIN dbo.mdl_enrol e ON e.id = ue.enrolid
     JOIN dbo.mdl_course c ON c.id = e.courseid
     --JOIN dbo.mdl_course_categories cc ON c.category = cc.id
     JOIN dbo.mdl_user_info_data id ON u.id = id.userid
     WHERE c.id = 3
          AND id.fieldid = 3
) t
GROUP BY t.data
于 2013-07-30T07:07:06.777 回答
2

尝试使用group by从句

SELECT mdl_user_info_data.data,count(1) as Total
FROM dbo.mdl_user, 
     dbo.mdl_course, 
     dbo.mdl_user_enrolments, 
     dbo.mdl_enrol, 
     dbo.mdl_course_categories,
     dbo.mdl_user_info_data
WHERE mdl_course.id = mdl_enrol.courseid AND 
      mdl_enrol.id = mdl_user_enrolments.enrolid AND 
      mdl_user_enrolments.userid = mdl_user.id AND 
      mdl_course.category = mdl_course_categories.id AND 
      mdl_course.id = 3 and
      mdl_user_info_data.fieldid = 3 and
      mdl_user.id = mdl_user_info_data.userid
group by 
      mdl_user_info_data.data

但请考虑以下解决方案

SELECT muid.data,count(1) as Total
FROM dbo.mdl_user mu, 
     dbo.mdl_course mc, 
     dbo.mdl_user_enrolments mue, 
     dbo.mdl_enrol me, 
     dbo.mdl_course_categories mcc,
     dbo.mdl_user_info_data muid
WHERE mc.id = me.courseid AND 
      me.id = mue.enrolid AND 
      mue.userid = mu.id AND 
      mc.category = mcc.id AND 
      mc.id = 3 and
      muid.fieldid = 3 and
      mu.id = muid.userid
group by muid.data

在上面的示例中,我为列添加了别名。使用它们是一种很好的做法,因为代码更具可读性。

于 2013-07-30T06:58:25.790 回答