我有一个表,其中有50-60列包含主数据,如下所示(仅为示例)。
我需要显示过滤器以允许客户过滤数据。因此结果将类似于以下内容,我将其绑定到网页上的下拉菜单。
所以,尽管我有一个FilterOptions表,该表告诉我要寻找哪个下拉过滤器的列,例如:
现在,我无法找出sql查询,我需要以第二张图片中所示的格式获取数据。可能需要透视MasterData表并与FilterOptions联接,但是如何确定并不确定。 任何帮助/指针表示赞赏。 谢谢
答案 0 :(得分:1)
我建议使用apply
:
select v.*
from t cross apply
(values ('Country', t.countryCode, t.countryName),
('Country', t.StateCode, t.StatueName),
('City', t.CityCode, t.CityName),
) v(label, key, value);
答案 1 :(得分:0)
您可以像下面这样使用unpivot
:
declare @master table(id int, countrycode varchar(10), countryname varchar(20), statecode varchar(10), statename varchar(20), citycode varchar(10), cityname varchar(20))
insert into @master
select 1, 'IN', 'INDIA', 'MH', 'Maharashtra', 'PNE', 'Pune'
union
select 2, 'US', 'USA', 'PA', 'Pennsylvania', 'PH', 'Philadelphia'
union
select 3, 'US', 'USA', 'NY', 'NewYork', 'NY', 'NewYork'
union
select 4, 'US', 'USA', 'NY', 'Pennsylvania', 'PT', 'NewYork'
declare @filters table (label varchar(20), [key] varchar(10), [value] varchar(20))
insert into @filters
select 'Country', 'IN', 'India'
union
select 'Country', 'US', 'USA'
union
select 'State', 'MH', 'MH'
union
select 'State', 'PA', 'Pennsylvania'
union
select 'City', 'NY', 'NewYork'
union
select 'City', 'PNE', 'Pune'
select id,cc countrycode, ccval, cn countryname, cnval, sc statecode, scval, sn statename, snval, cic citycode, cival, cin cityname, cinval
into #temp
from
(
select id, countrycode, countryname, statecode, statename, citycode, cityname
from @master
)t
unpivot
(
cc for ccval in (countrycode)
)upvtcountry
unpivot
(
cn for cnval in (countryname)
)upvtcountryname
unpivot
(
sc for scval in (statecode)
)upvtstate
unpivot
(
sn for snval in (statename)
)upvtstatename
unpivot
(
cic for cival in (citycode)
)upvtcity
unpivot
(
cin for cinval in (cityname)
)upvtcityname
select distinct f.label, case f.label when 'City' then t.cival when 'Country' then t.ccval when 'State' then t.scval end keycolumnname
,case f.label when 'City' then t.cinval when 'Country' then t.cnval when 'State' then t.snval end valucolumnname
from #temp t
left join @filters f
on f.[key] = case f.label when 'City' then t.citycode when 'Country' then t.countrycode when 'State' then t.statecode end
drop table #temp