以自訂格式按月和年進行SQL 分組
在SQL 中使用時間戳記時,以特定將資料分組非常有用間隔,例如幾個月或幾年。但是,DATE 或 TIMESTAMP 資料類型的預設格式可能不會總是與所需的表示形式一致。在這方面,一個常見的挑戰是以自訂格式顯示日期,例如「月-年」。
考慮以下 SQL 查詢:
SELECT MONTH(date) + '.' + YEAR(date) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada FROM [Order] WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3') GROUP BY MONTH(date), YEAR(date)
此查詢將按月和年顯示數據,並顯示行銷費用和收入的合計金額。但是,第一列「Mjesec」目前僅顯示月份,例如「9」。要修改輸出以顯示“月-年”,需要結合使用轉換和字串連接。
一種方法是將月份和年份值轉換為字串,然後手動連接它們:
SELECT CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4)) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada FROM [Order] WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3') GROUP BY CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4))
這將輸出所需的「月-年」格式,例如「9 -2011」。或者,按照 40-Love 的建議,可以使用前導零執行轉換,從而產生以下 GROUP BY 子句:
GROUP BY CAST(YEAR(date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(date) AS VARCHAR(2)), 2)
此變體添加前導零以確保月份始終顯示為兩個- 數字。
以上是如何以自訂「月-年」格式按月和年對 SQL 資料進行分組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!