在查询中添加Group By和计数变量

时间:2015-07-28 10:09:14

标签: sql sql-server

我在这里有这个问题:

SELECT nsd.REGISTRATION_DATE,nsd.Subject_Name,nsd.Subject_Code,nsda.District_Name, nsda.Region_Name
    FROM tbl1 AS nsd 
    LEFT JOIN
    tbl2 AS nsda ON nsd.Subject_Code = nsda.Subject_Code

我需要按Subject_Name, District_Name and Region_Name.对此查询进行分组我还想添加一个告诉我的计数器:

Subject|Nr.Total| Region| District
Maths   2        Austria Tyrol
Maths   5        Austria Vienna

当我尝试添加组时,我得到一个错误,它说了一些关于聚合函数的内容:

  

Msg 8120,Level 16,State 1,Line 1 Column' tbl1.REGISTRATION_DATE'是   在选择列表中无效,因为它不包含在任何一个中   聚合函数或GROUP BY子句。

提前致谢。

4 个答案:

答案 0 :(得分:0)

    SELECT nsd.Subject_Name AS [Subject], count(*) AS [Nr.Total], nsda.Region_Name AS [Region], nsda.District_Name AS [District]
    FROM tbl1 AS nsd 
    LEFT JOIN
    tbl2 AS nsda ON nsd.Subject_Code = nsda.Subject_Code
Group by nsd.Subject_Name, nsda.Region_Name, nsda.District_Name

如果您需要' tbl1.REGISTRATION_DATE'在select中,也可以在Group By语句中添加它。

答案 1 :(得分:0)

由于您未在REGISTRATION_DATE中使用SELECT,因此可以省略它。

SELECT
    nsd.Subject_Name,
    [Nr. Total] = ISNULL(COUNT(nsda.Subject_Code), 0),
    nsda.Region_Name,
    nsda.District_Name
FROM tbl1 nsd
LEFT JOIN tbl2 nsda
    ON nsd.Subject_Code = nsda.Subject_Code
GROUP BY nsd.Subject_Name, nsda.Region_Name, nsda.District_Name

在SQL Server中,SELECT中的列必须出现在GROUP BY子句中。

答案 2 :(得分:0)

尝试此查询: -

SELECT nsd.REGISTRATION_DATE, nsd.Subject_Name, nsd.Subject_Code, nsda.District_Name, nsda.Region_Name, COUNT(*)
FROM tbl1 AS nsd 
LEFT JOIN
tbl2 AS nsda ON nsd.Subject_Code = nsda.Subject_Code
GROUP BY nsd.REGISTRATION_DATE, nsd.Subject_Name, nsd.Subject_Code, nsda.District_Name, nsda.Region_Name

答案 3 :(得分:0)

试试这个:

SELECT nsd.Subject_Name as Subject, count(*) as 'Nr.Total', nsd.Region_Name as Region, nsd.District_Name as District
FROM tbl1 AS nsd 
LEFT JOIN
tbl2 AS nsda ON nsd.Subject_Code = nsda.Subject_Code
GROUP BY nsd.Subject_Name, nsd.District_Name, nsd.Region_Name