在 SQL 中,有多種高效的數(shù)據(jù)轉換方法。以下是一些常見的數(shù)據(jù)轉換方法:
示例:
-- 使用 CAST() 函數(shù)
SELECT CAST(column_name AS new_data_type) FROM table_name;
-- 使用 CONVERT() 函數(shù)(針對 SQL Server)
SELECT CONVERT(new_data_type, column_name) FROM table_name;
示例:
-- 提取并轉換日期字符串的年份部分
SELECT CAST(LEFT(date_column, 4) AS INTEGER) AS year FROM table_name;
示例:
-- 獲取當前日期的年份
SELECT DATEPART(year, GETDATE()) AS current_year;
示例:
-- 將性別轉換為 'Male' 或 'Female'
SELECT CASE WHEN gender = 'M' THEN 'Male' ELSE 'Female' END AS gender_text FROM table_name;
示例:
-- 使用 PIVOT 將行數(shù)據(jù)轉換為列數(shù)據(jù)
SELECT * FROM (
SELECT customer_id, product_id, quantity FROM sales_data
) AS source_table
PIVOT (
SUM(quantity) FOR product_id IN ([1], [2], [3])
) AS pivot_table;
示例:
-- 計算每個部門的員工平均年齡
SELECT department, AVG(age) AS average_age FROM employees
GROUP BY department;
示例:
-- 使用 INNER JOIN 將兩個表的數(shù)據(jù)合并
SELECT e.employee_id, e.name, d.department_name FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;
根據(jù)具體的需求和場景,可以選擇適當?shù)臄?shù)據(jù)轉換方法。在實際應用中,可能需要結合多種方法來實現(xiàn)復雜的數(shù)據(jù)轉換。