mysql中记录出现次数的统计

8i9zcol2  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(420)

我试图计算哺乳期,这意味着我在计算一只动物的产犊日期:当动物的产犊日期发生变化时,1被加到哺乳ID中以保持计数。这是五列


# ID,LactationID,CalvDateLactationID, animalidLactationID,animalid, calvDate

'1', '1', '1 - 2018-08-08', '1 - T81', 'T81', '2018-08-08'
'2', '1', '1 - 2017-12-18', '1 - T66', 'T66', '2017-12-18'
'3', '2', '3 - 2017-12-28', '4 - T66', 'T66', '2017-12-28'

我用来生成这个输出的查询是

SELECT 
  dt.ID,
  @row_num := IF(@aid <> dt.animalid, 1, @row_num + 1) as LactationID,
  concat(@row_num := IF(@aid <> dt.animalid, 1, @row_num + 1),' - ',calvDate) AS CalvDateLactationID,
  concat(@row_num := IF(@aid <> dt.animalid, 1, @row_num + 1),' - ',animalid) AS animalidLactationID, 
  @aid := dt.animalid AS animalid,  dt.calvDate 
FROM 
(SELECT ID,animalid,calvDate FROM calvingdatecombined ORDER BY animalid, calvDate, ID) AS dt 
CROSS JOIN (SELECT @row_num := 0, @aid := '') AS user_init_vars 
where calvDate <> '' and calvDate <> '0000-00-00' ORDER BY dt.ID

我的预期产出是


# ID, LactationID,CalvDateLactationID, animalidLactationID,animalid, calvDate

'1', '1', '1 - 2018-08-08', '1 - T81', 'T81', '2018-08-08'
'2', '1', '1 - 2017-12-18', '1 - T66', 'T66', '2017-12-18'
'3', '2', '2 - 2017-12-28', '2 - T66', 'T66', '2017-12-28'

我可以在查询中改进什么来帮助生成预期的输出。
我的calvingdatecombined表包含以下列和示例数据


# ID, animalid, calvDate

'1', 'T81', '2018-08-08' 
'2', 'T66', '2017-12-18'
'3', 'T66', '2017-12-28'
vtwuwzda

vtwuwzda1#

不是一个答案,只是一个建议,太长了,不能发表评论:
这样的数据集不会失去任何意义,而且更易于阅读:

ID, animalid, calvDate
186, 81, '2018-08-08'
188, 66, '2017-12-18'
189, 66, '2017-12-28'
3z6pesqy

3z6pesqy2#

你不需要增加 @row_num 再次重视 CalvDateLactationID 以及 animalidLactationID .
而且,我已经改变了方向 Where 条件 calvDate 内部选择查询,以便进一步优化。请改用以下查询:

SELECT 
  dt.ID,
  @row_num := IF(@aid <> dt.animalid, 1, @row_num + 1) as LactationID,
  concat(@row_num, ' - ', calvDate) AS CalvDateLactationID,
  concat(@row_num, ' - ', animalid) AS animalidLactationID, 
  @aid := dt.animalid AS animalid,  
  dt.calvDate 
FROM 
(
 SELECT ID,animalid,calvDate 
 FROM calvingdatecombined 
 WHERE calvDate > '0000-00-00' 
 ORDER BY animalid, calvDate, ID
) AS dt 
CROSS JOIN (SELECT @row_num := 0, 
                   @aid := '') AS user_init_vars 
ORDER BY dt.ID

相关问题