我想加入两个表并将其合并为一个但问题是一个表是横向格式,另一个是垂直的
以下是表格结构 表1:
@Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.fragment_container, new **your_first_fragment**()).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
表2:
EmpID | Code | Name | Fld1 | Fld2 | Fld3 | Fld4
-- |---- | ------| --- | ---- |---- |----
1 | 1008M | ABC | temp1 | temp2 | temp3 | null
2 | 1039E | XYZ | temp1 | null | null | null
3 | 1040E | TYS | null | null | null | temp6
期望的输出:
EmpID | FieldName | Value
-- |---- | ------
1 | FH | 1000
1 | FB | 1220
2 | FHRA | 3000
2 | FB | 3000
3 | FB | 3000
我曾尝试使用Pivot查询,但它没有按预期工作。
答案 0 :(得分:1)
Select
现在加入临时表和表1。
答案 1 :(得分:1)
您必须使用如下的动态查询,您可以通过添加更多FieldName
s
CREATE TABLE #table1(EmpID INT,
Code VARCHAR(20),
Name VARCHAR(20),
Fld1 VARCHAR(20),
Fld2 VARCHAR(20),
Fld3 VARCHAR(20),
Fld4 VARCHAR(20))
INSERT INTO #table1 VALUES
(1, '1008M','ABC','temp1','temp2','temp3',NULL),
(2, '1039E','XYZ','temp1',NULL,NULL,null),
(3, '1040E','TYS',null,NULL,NULL,'temp6')
CREATE TABLE #table2(EmpID INT, FieldName VARCHAR(20), VALUE INT)
INSERT INTO #table2 VALUES
(1,'FH',1000),
(1,'FB',1220),
(2,'FHRA',3000),
(2,'FB',3000),
(3,'FB',3000)
DECLARE @col VARCHAR(MAX)
DECLARE @sql VARCHAR(MAX)
SELECT @col = COALESCE(@col + ', ','') + QUOTENAME(FieldName)
FROM #table2 GROUP BY FieldName
SELECT @col -- This gives: [FB], [FH], [FHRA]
-- Now setting this @col variable in the Dynamic SQL.
SET @sql = '
select EmpID, Code, Name,Fld1,Fld2,Fld3,Fld4, ' + @col + '
from (select a.EmpID, Code, Name,Fld1,Fld2,Fld3,Fld4, b.FieldName, b.value
from #table1 a
join #table2 b on a.empid=b.empid)p
PIVOT(MAX (VALUE) FOR FieldName IN ( ' + @col + ' )
) AS pvt
'
PRINT @sql
EXEC (@sql)
<强>输出强>:
EmpID Code Name Fld1 Fld2 Fld3 Fld4 FB FH FHRA
1 1008M ABC temp1 temp2 temp3 NULL 1220 1000 NULL
2 1039E XYZ temp1 NULL NULL NULL 3000 NULL 3000
3 1040E TYS NULL NULL NULL temp6 3000 NULL NULL
答案 2 :(得分:1)
试试这个工作正常
;with demo1 as (
select * from Table_1
), a as
(
SELECT *
FROM Table_2
PIVOT(SUM(value)
FOR Fieldname IN (FH, FB,FHRA)) AS PVTTable
)select demo1.EmpID,demo1.Code,demo1.Name,demo1.Fld1,demo1.Fld2,demo1.Fld3,demo1.Fld4,a.FH,a.FB,a.FHRA
from a inner join demo1 on a.EmpID=demo1.EmpID
<强>输出:强>
答案 3 :(得分:0)
试试这个:
select t1.empid,
t1.code,
t1.fld1,
t1.fld2,
t1.fld3,
t1.fld4,
sum(case when t2.fieldname = 'FH' then t2.value else 0 end) FH,
sum(case when t2.fieldname = 'FB' then t2.value else 0 end) FB,
sum(case when t2.fieldname = 'FHRA' then t2.value else 0 end) FHRA
from table1 t1
left outer join table2 t2
on t1.empid = t2.empid
group by t1.empid,
t1.code,
t1.fld1,
t1.fld2,
t1.fld3,
t1.fld4;