我跟随sql查询
SELECT animal_code, ISNULL(SUM(calve_milk + morning + evening), 0) / 30 AS [Sep 2011],
(SELECT ISNULL(SUM(calve_milk + morning + evening), 0) / 31 AS Expr1
FROM dbo.Status
WHERE (m_date BETWEEN '10/1/2011' AND '10/31/2011')) AS [Oct 2011]
FROM dbo.Status AS Status_1
WHERE (m_date BETWEEN '9/1/2011' AND '9/30/2011')
GROUP BY animal_code
ORDER BY animal_code
通过这个查询,我计算了一个日期范围之间的总和,并将其命名为[2011年9月],现在我必须计算[动态代码]对它进行分组的[oct 2011]总和,但我认为固定列只能在子查询但是在子查询中我无法通过动物代码对总和进行分组请任何人帮助我通过子查询中的animal_code获取该总和
更新
select a.animal_code,a.Sep2011,b.Oct2011 from
(SELECT DISTINCT Images.animal_code,
REPLACE(REPLACE(ROUND(ISNULL(SUM(Status.calve_milk + Status.morning + Status.evening), 0) / 30, 0), '.', ''), '0', '') Sep2011
FROM Images,Status,animal_Status
where Images.animal_code=Status.animal_code
and Images.status_id=animal_status.status_id
and status.m_date between '9/1/2011' and '9/30/2011'
and animal_status.status_id=8
group by animal_code) a,
(SELECT DISTINCT Images.animal_code,
REPLACE(REPLACE(ROUND(ISNULL(SUM(Status.calve_milk + Status.morning + Status.evening), 0) / 31, 0), '.', ''), '0', '') Oct2011
FROM Images,Status,animal_Status
where Images.animal_code=Status.animal_code
and Images.status_id=animal_status.status_id
and status.m_date between '10/1/2011' and '10/31/2011'
and animal_status.status_id=8
group by animal_code) b
where a.animal_code=b.animal_code
答案 0 :(得分:1)
我很遗憾你还没有看到我的上一条评论
好的,我模拟你的桌子,我做这个聪明的查询(我猜:)):
SELECT septable.code, septable.sep, octtable.oct
FROM (SELECT code, ISNULL(SUM(mor + milk + ev), 0) / 30 AS sep
FROM status
WHERE (m_date BETWEEN '09/01/2011' AND '09/30/2011')
GROUP BY code) AS septable INNER JOIN
(SELECT code, ISNULL(SUM(mor + milk + ev), 0) / 31 AS oct
FROM status AS status_1
WHERE (m_date BETWEEN '10/01/2011' AND '10/30/2011')
GROUP BY code) AS octtable ON octtable.code = septable.code
答案 1 :(得分:0)
您无法使用其他列扩展查询以包含新月而不会产生垃圾。在电子表格或其他地方这样做。
尝试将此作为您的查询。 它没有确切的格式,因为它将结果显示为行而不是列,但它适用于所有月份和未来月份。 我用本月的确切天数替换了30,也显示了2位数而不是总是向下舍入的结果。 我选择向您展示在结果中显示月份和年份的两种不同方式
SELECT animal_code, SUM(isnull(calve_milk,0) + isnull(morning,0) + isnull(evening,0)) /
-- this replaces your 30
cast(datediff(day, dateadd(month, datediff(month, 0, m_date), 0), dateadd(month, datediff(month, 0, m_date) + 1, 0)) as decimal(9,2))
AS average_milk_per_day,
--this will give you a varcharcolumn showing month and year
stuff(convert(varchar(11), dateadd(month,datediff(month, 0, m_date), 0), 100)
, 4,3,'') monthyear,
--this will give you the month and year as a datetime
dateadd(month, datediff(month, 0, m_date),0) monthyear_as_date
FROM dbo.Status AS Status_1
WHERE m_date >= '2011-01-09'
GROUP BY animal_code,
datediff(month, 0, m_date)
ORDER BY datediff(month, 0, m_date), animal_code
当前月份的结果将会降低,直到所有数据都被注册为止。如果你只需要为注册日而不是整月计算,请告诉我,我会再次调整查询。