drevls8138 2013-08-07 15:03
浏览 39
已采纳

SQL - 使用SUM计算GROUP中有多少项

I'm using PDO (still learning) and have the current SQL query. This works perfectly, merging duplicate entries and adding their value. Is there a way I could see how many duplicate entries there were?

$SQL = "SELECT Col1, SUM(Col2) FROM table WHERE Date > :FromDate AND Date < :EndDate GROUP BY Col1";

My table looks like this

Col1     Col2 
-----  ------
ABC       2
ABA       3
ADD       1
AED       3
ABC       2
ABA       3
ADD       1
AED       3
AED       0

At the moment, after I loop through, the result looks like this

Col1    Col2    
----    ----    
ABC       4
ABA       6
ADD       2
AED       6

But i'd like to get the value of how many times it occured in the DB before it was grouped so i could end up with

Col1    Col2    Times Appeared
----    ----    --------------
ABC       4           2
ABA       6           2
ADD       2           2
AED       6           3
  • 写回答

3条回答 默认 最新

  • dtol41388 2013-08-07 15:04
    关注

    Use count() for that. It counts only the records in a group if used with group by

    SELECT Col1, SUM(Col2), count(*) as 'Times appeared'
    FROM table 
    WHERE Date > :FromDate AND Date < :EndDate 
    GROUP BY Col1"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用