在sql server 2012中计算结果

时间:2013-07-30 06:56:30

标签: sql sql-server sql-server-2012

我在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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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