如何选择特定值并将其加入第一个结果集

时间:2018-05-31 09:20:26

标签: mysql sql

我有一个select语句,它从表中返回一些列。 我有一个“daySince”栏目(第3个),实际上是日期差异。

我需要再选择一列(作为numberOfRecord),它代表具有相同“daySince”值的行数。 我只是在这里附加数字7来解释结构的样子,即使该列的正确值是:

  • 1对于具有daySince val且介于10和14之间的行

  • 8对于具有daySince val 15

  • 的行
  • 2对于具有daySince val 16

  • 的行

希望我所问的确实有意义。 我尝试运行一些随机的左,右和全外连接,结果很糟糕。 任何人都能以正确的方式对我说话吗?

这是示例查询

<log4net>
<appender name="ErrorsLog" type="log4net.Appender.RollingFileAppender">
  <file value="${PROGRAMDATA}\DEVIT\eProc\" />
  <appendToFile value="true" />
  <param name="DatePattern" value="yyyy-MM-'CadRmsSyncService_Errors.log'" />
  <staticLogFileName value="false" />
  <maximumFileSize value="100GB" />
  <maxSizeRollBackups value="0" />
  <param name="Threshold" value="WARN" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%d [%t] %-5p - %m%n" />
  </layout>
</appender>
<appender name="InfoLog" type="log4net.Appender.RollingFileAppender">
  <file value="${PROGRAMDATA}\DEVIT\eProc\" />
  <appendToFile value="true" />
  <param name="DatePattern" value="yyyy-MM-'CadRmsSyncService_Info.log'" />
  <staticLogFileName value="false" />
  <maximumFileSize value="100GB" />
  <maxSizeRollBackups value="0" />
  <param name="Threshold" value="DEBUG" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%d [%t] %-5p - %m%n" />
    <IgnoresException value="False" />
  </layout>
  <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="DEBUG" />
    <levelMax value="FATAL" />
  </filter>
</appender>
<root>
  <level value="DEBUG"/>      
  <appender-ref ref="ErrorsLog" />
  <appender-ref ref="InfoLog" />
</root>
SELECT username, id, DATEDIFF( creation, '2018/02/28') as daySince, 7 as numberOfRecord
FROM MyTable 
ORDER BY daySince ASC

2 个答案:

答案 0 :(得分:1)

检查这个。

        SELECT
            username, id, 
            DATEDIFF( creation, '2018/02/28') as daySince, 
            Count(DATEDIFF( creation, '2018/02/28')) as numberOfRecord
        FROM MyTable 
        Group By DATEDIFF( creation, '2018/02/28')
        ORDER BY daySince ASC

答案 1 :(得分:0)

根据您的需要,您应该按username, id汇总:

SELECT username, id, DATEDIFF(creation, '2018-02-28') as daySince, COUNT(*)
FROM MyTable 
GROUP BY username, id, DATEDIFF( creation, '2018-02-28')
ORDER BY daySince ASC;

或者您应该删除usernameid,因为它们无关紧要:

SELECT DATEDIFF(creation, '2018-02-28') as daySince, COUNT(*)
FROM MyTable 
GROUP BY DATEDIFF( creation, '2018-02-28')
ORDER BY daySince ASC;