我有一个包含字段的表格:
Client_ID, Date, Value
每年12个月中每一个都有一个条目(即每个客户12个条目)。
我想创建一个每个Client_ID只有一行的表,其中包含每个月的所有值。类似的东西:
Client_ID, Date_January, Value_January, Date_February, Value_February, ........, Date_December, Value_December
有人可以帮我查询吗?
这就是我要做的事情(不工作......):
select
Client_Id,
case when ((strftime('%m', Date) = '01')) then
Date as Date_January,
Value as Value_January,
else null end
case when ((strftime('%m', Date) = '01')) then
Date as Date_February,
Value as Value_February,
else null end
....
from Test_Table
where
strftime('%Y', Date) = '2013'
答案 0 :(得分:1)
首先,您需要解开案例构造,因为它们会生成单个值。使用:
case
when ((strftime('%m', Date) = '01')) then Date
else null
end as Date_January,
case when ((strftime('%m', Date) = '01')) then Value
else null
end as Value_January,
然后,如果您希望每个客户端占一行,请使用GROUP BY ClientID。
第三个问题是如何将所有Date_January列聚合成一行。如果您确实知道每个客户端每月只有一行,您可以使用MAX()知道not null值将高于NULL值:
select
Client_Id,
MAX(case
when ((strftime('%m', Date) = '01')) then Date
else null
end) as Date_January,
MAX(case when ((strftime('%m', Date) = '01')) then Value
else null
end) as Value_January,
MAX(case
when ((strftime('%m', Date) = '02')) then Date
else null
end) as Date_February,
MAX(case when ((strftime('%m', Date) = '02')) then Value
else null
end) as Value_February,
....
from Test_Table
where
strftime('%Y', Date) = '2013'
group by Client_Id;