日期:2014-05-17 浏览次数:20598 次
CREATE TABLE phonetable(phone VARCHAR(100), pwd VARCHAR(100))
INSERT phonetable SELECT '123456789', 'pwd' UNION ALL SELECT '987654321', 'pwd'
CREATE TABLE balance(phone VARCHAR(100), query_date VARCHAR(10), balance float)
INSERT balance
select '123456789','20120725', 12.5 union all
select '123456789','20130725', 25 union all
select '123456789','20140725', 50 union all
select '987654321','20130101', 60
--静态sql,仅供参考:
SELECT *
FROM
(
SELECT a.phone, b.query_date, b.balance
FROM phonetable A
LEFT JOIN balance B
ON a.phone = b.phone
) T
PIVOT
(
MAX(balance) FOR query_date
IN([20120725],[20130101], [12130725], [20140725]) --日期不固定的情况下,只能用拼SQL实现
) M
--拼SQL
DECLARE @datelist NVARCHAR(max), @sql NVARCHAR(MAX)
SELECT @datelist = N'', @sql = N''
SELECT @datelist = @datelist + ',' + QUOTENAME(query_date)
FROM balance ORDER BY query_date
SET @sql = N'
SELECT *
FROM
(
SELECT a.phone, b.query_date, b.balance