从表中按年,月和周选择数据

时间:2011-11-08 22:18:21

标签: mysql sql

我有以下表格:

Table: promotion_asset
promotion_id
asset_id

(促销可以有很多资产)

Table: promotion_tracking
id(PK)
asset_id
date_scanned

(每次扫描资产时的记录表)

我想在一个查询中尝试能够识别特定促销ID中的资产被扫描的次数:今年,本月和本周。

我尝试了很多不同的方法,但找不到能够返回正确结果的单个查询。

1 个答案:

答案 0 :(得分:1)

我只有sql server,所以我能够测试年份和月份功能,查看WeekOfYear mysql

SELECT pa.promotion_id
   , SUM(CASE
        WHEN YEAR(pt.date_scanned) = YEAR(GETDATE()) THEN 1
        ELSE 0
     END CASE) AS ThisYear
   , SUM(CASE
        WHEN YEAR(pt.date_scanned) = YEAR(GETDATE())
           AND MONTH(pt.date_scanned) = MONTH(GETDATE()) THEN 1
        ELSE 0
     END CASE) AS ThisMonth
   , SUM(CASE
        WHEN WEEKOFYEAR(pt.date_scanned) = WEEKOFYEAR(GETDATE()) THEN 1
        ELSE 0
     END CASE) AS ThisWeek
FROM promotion_tracking AS pt
INNER JOIN promotion_asset AS pa ON pt.asset_id = pa.asset_id
GROUP BY pa.promotion_id