用SQL Server中的实际值替换Id

时间:2014-11-20 11:54:21

标签: c# sql sql-server sql-server-2008

我有以下表结构也提到我的预期输出请帮我查询,因为我对SQL查询不太了解

查询:

SELECT * FROM(
SELECT ESIDispensary,ESILocation,test,Category, COUNT(*) AS [Total Count]
FROM
    (SELECT category,ESILOCATION,ESIDISPENSARY,TEST 
    FROM(SELECT id,CompanyId,FName,Code,category,ESILOCATION,ESIDISPENSARY
         FROM dbo.[EmployeeDetail] e  WHERE e.CompanyId = 1 AND Category in (1,2)) a 
    LEFT JOIN 
    (SELECT * 
     from 
        (SELECT EmployeeId, CustomeFieldName,FieldValue 
         FROM dbo.[CustomeFieldDetail] C  
         JOIN dbo.[EmployeeDetail]  e ON e.id = c.employeeid AND e.CompanyId = c.companyid  
         WHERE e.CompanyId = 1 AND Category IN (1,2)) SRC 
PIVOT 
(MAX(FieldValue) FOR CustomeFieldName IN([TEST])) 
piv)  
b ON a.Id = b.EmployeeId 
) AS a
GROUP BY  ESIDispensary ,ESILocation,test,Category) x

使用上述查询生成的表格

ESIDispensary   ESILocation test    Category    Count
12                11        NULL       1        NULL
12                13        30         1        1
14                13        29         2        2 

表1:ESI

Id  CompanyId   FieldName        ComboValue 
11      1       ESILOCATION        mumbai   
12      1       ESIDISPENSARY      mumbai   
13      1       ESILOCATION        pune     
14      1       ESIDISPENSARY      pune     
29      1       TEST               HDFC     
30      1       TEST               ICICI    

表2:类别

id   CategoryName
1     staff
2     manager

问题是我想用期望的值替换ID也可以更改上面的查询以获得预期的结果

预期摘要输出:

ESIDispensary   ESILocation test      staff     manager
mumbai           mumbai     NULL       1        NULL
mumbai           pune       ICICI      1        1
pune             pune       HDFC      NULL      2 

1 个答案:

答案 0 :(得分:1)

这是你想要的:

SELECT (SELECT ComboValue FROM ESI WHERE ID = ESIDispensary) AS  ESIDispensary,
            SELECT ComboValue FROM ESI WHERE ID = ESILocation) AS  ESILocation,
            SELECT ComboValue FROM ESI WHERE ID = test) AS  test,
            Category, [Total Count]
    FROM
    (
        SELECT ESIDispensary,ESILocation,test,Category, COUNT(*) AS [Total Count]
        FROM
            (SELECT category,ESILOCATION,ESIDISPENSARY,TEST 
            FROM(SELECT id,CompanyId,FName,Code,category,ESILOCATION,ESIDISPENSARY
                 FROM dbo.[EmployeeDetail] e  WHERE e.CompanyId = 1 AND Category in (1,2)) a 
            LEFT JOIN 
            (SELECT * 
             from 
                (SELECT EmployeeId, CustomeFieldName,FieldValue 
                 FROM dbo.[CustomeFieldDetail] C  
                 JOIN dbo.[EmployeeDetail]  e ON e.id = c.employeeid AND e.CompanyId = c.companyid  
                 WHERE e.CompanyId = 1 AND Category IN (1,2)) SRC 
        PIVOT 
        (MAX(FieldValue) FOR CustomeFieldName IN([TEST])) 
        piv)  
        b ON a.Id = b.EmployeeId 
    ) AS a
    GROUP BY  ESIDispensary, ESILocation, test, Category) x