3

有一个查询可以返回过去 7 天的销售数据。如何获得过去 30 天的销售额(查看过去 7 天和最后 30 天的销售额)?

SELECT 
  a.row_id,
  MAX(ad.new_value) - MIN(ad.new_value) AS sales7days 
FROM
  _audit a 
  LEFT JOIN _audit_data ad 
    ON a.audit_id = ad.audit_id 
WHERE ad.col = 'sales' 
  AND a.triggered_datetime > NOW() - INTERVAL 7 DAY 
GROUP BY a.row_id 
ORDER BY sales7days DESC;
4

2 回答 2

2

也许用一个CASE表达:

SELECT a.row_id
   ,  MAX(case when a.triggered_datetime > NOW() - INTERVAL 7 DAY 
               then ad.new_value else NULL end)
    - MIN(case when a.triggered_datetime > NOW() - INTERVAL 7 DAY
               then ad.new_value else NULL end) AS sales7days 
   ,  MAX(case when a.triggered_datetime > NOW() - INTERVAL 30 DAY 
               then ad.new_value else NULL end)
    - MIN(case when a.triggered_datetime > NOW() - INTERVAL 30 DAY
               then ad.new_value else NULL end) AS sales30days 
FROM  _audit a, _audit_data ad 
WHERE a.audit_id = ad.audit_id AND ad.col = 'sales' 
GROUP BY a.row_id;
于 2012-12-31T20:38:30.343 回答
1
SELECT 
  d7.row_id,
  d7.salesdays, d30.salesdays
FROM
(
  Select a.row_id, MAX(ad.new_value) - MIN(ad.new_value) AS salesdays
  From _audit a 
  LEFT JOIN _audit_data ad ON a.audit_id = ad.audit_id 
WHERE ad.col = 'sales' AND a.triggered_datetime > NOW() - INTERVAL 7 DAY 
GROUP BY a.row_id 
) d7,
(
  Select a.row_id, MAX(ad.new_value) - MIN(ad.new_value) AS salesdays
  From       _audit a 
  LEFT JOIN _audit_data ad ON a.audit_id = ad.audit_id 
WHERE ad.col = 'sales' AND a.triggered_datetime > NOW() - INTERVAL 30 DAY 
GROUP BY a.row_id 
) d30

where d7.row_id = d30.row_id
ORDER BY sales7days DESC;

假设您希望两者都使用相同的行 ID - 并且要显示任一值,您可能希望也可能不希望将其设置为内部或外部连接和/或 COALESCE 值字段(对数据了解不足)。

于 2012-12-31T20:51:34.297 回答