简体   繁体   English

SQL-使用COUNT查询出现问题

[英]SQL - Trouble using COUNT query

Good day again to all SQL guru here :) 再次祝所有SQL专家今天好:)

I have a problem querying my table using COUNT. 我在使用COUNT查询表时遇到问题。

This is the data inside of the table (tblstudentoffense) 这是表内的数据(tblstudentoffense)

在此处输入图片说明

And this is the RESULT that I want (Let's say that there is a new column after the offenseType that will count the Stealing and Gaming Offense 这就是我想要的结果(假设在AttackType之后有一个新列,该列将计入偷窃和游戏攻击

在此处输入图片说明

Is this possible? 这可能吗? If possible kindly add an explanation with your provided code. 如果可能,请在提供的代码中添加解释。 Thanks :) 谢谢 :)

Using subquery to get count and concatenate count with main select statement 使用子查询获取计数并将计数与主选择语句连接

SELECT DISTINCT OffenseType + ' ' + CAST(B.Cnt AS VARCHAR) ,  
Othercolumn1,Othercolumn2
FROM Your_tableName A
JOIN 
(
  SELECT COUNT(*) Cnt , StudentId
  FROM Your_tableName
  GROUP BY StudentId 
) B ON B.StudentId = A.StudentId

Try using CONCAT_WS() .The CONCAT_WS() function is used to join two or more strings with a separator. 尝试使用CONCAT_WS()CONCAT_WS()函数用于使用分隔符连接两个或多个字符串。

Note: offensetypeCount is an new column having expected output. 注意: encentypeCount是具有预期输出的新列。

SELECT *,CONCAT_WS(' ',offensetype,count(offenseType) AS offensetypeCount FROM tblstudentoffense GROUP BY offensetype;

Is this what you are looking for: 这是你想要的:

 WITH SRC AS  
    (SELECT 'STEALING' OFFENSETYPE,'1' STUDENTID FROM DUAL UNION ALL 
     SELECT 'STEALING' OFFENSETYPE,'1' STUDENTID FROM DUAL UNION ALL
     SELECT 'STEALING' OFFENSETYPE,'1' STUDENTID FROM DUAL UNION ALL
     SELECT 'STEALING' OFFENSETYPE,'1' STUDENTID FROM DUAL UNION ALL
     SELECT 'GAMING' OFFENSETYPE,'1' STUDENTID FROM DUAL UNION ALL)  
     SELECT OFFENSETYPE,STUDENTID,COUNT(*) FROM SRC GROUP BY OFFENSETYPE,STUDENTID;

You could try 你可以试试

SELECT CONCAT(offensetype, ' ', COUNT(offensetype)) AS offenseType, 
       studentid, 
       offenseln, 
       offensefn, 
       offensemn, 
       offensesuffixname 
FROM   tblstudentoffense
GROUP  BY offensetype, 
          studentid, 
          offenseln, 
          offensefn, 
          offensemn, 
          offensesuffixname; 

I've created a sample at this link http://rextester.com/WZGW41761 . 我在此链接http://rextester.com/WZGW41761上创建了一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM