sql语句的查询问题
2个表,表结构如下
phonetable(phone,pwd)//电话表
balance(phone,query_date,balance)//不同日期的余额
例子数据如下
phonetable
123456789 pwd
987654321 pwd
balance
phone query_date balance
123456789 20120725 12.5
123456789 20130725 25
123456789 20140725 50
987654321 20130101 60
现在需要列出所有号码的不同日期的余额,结果如下
号码 20120725 20130101 12130725 20140725
123456789 12.5 25 50
987654321 60
想了半天不知道怎么做,那位高人能给出解决方案呢?
[解决办法]
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
FROM phonetable A
LEFT JOIN balance B
ON a.phone = b.phone
) T
PIVOT
(
MAX(balance) FOR query_date
IN('+ STUFF(@datelist,1,1,'') +')--日期不固定的情况下,只能用拼SQL实现
) M
'
--PRINT @sql
EXEC(@sql)
/*
phone20120725201301012013072520140725
12345678912.5NULL2550
987654321NULL60NULLNULL
*/
set @sql = '[' + @sql + ']'
exec ('select * from balance a pivot (max(balance) for query_date in (' + @sql + ')) b')
go