2010-03-07 117 views
1

我是數據庫的新手。我用兩張桌子遇到了一個奇怪的問題。請讓我知道解決方案。請測量值低於加入 - 兩張表

一個ProductCentre表 prdcntrId(主鍵),prdcntrname場景

一個ApplicationType表 apptypeid(主鍵) prdcntreid(外鍵ProductCentre) apptypname

ProductCentre table  ||   ApplicationType table 
          || 
prdcntrId prdcntrname ||  apptypeid prdcntreid apptypname 
001   Delhi  ||   11   001   Busines 
002   Mumbai  ||   12   003   Engg 
003   Hyd   ||   13   001   Soft 
             14   002   Science 

最終結果應該是這樣的 產品中心可以有任何類型的應用程序,如德里可以有許多業務,軟應用程序與孟買相同,hyd

 
--------------------------------------------------------------------- 
prdcntrname    Busines  Engg Soft  Science 
--------------------------------------------------------------------- 
Delhi      1    0  1   0 
--------------------------------------------------------------------- 
Mumbai      0    1  0   1 
--------------------------------------------------------------------- 
Hyd      0    1  0   0 
--------------------------------------------------------------------- 

這個解決方案可能來自這兩個表。請幫我在這種情況下

感謝, KK

+0

它被稱爲表旋轉。 – 2010-03-07 18:48:37

回答

3

您可以嘗試使用PIVOT

喜歡的東西(SQL Server)的

DECLARE @ProductCentre table(
     prdcntrId INT, 
     prdcntrname VARCHAR(50) 
) 

DECLARE @ApplicationType table(
     apptypeid INT, 
     prdcntreid INT, 
     apptypname VARCHAR(50) 
) 

INSERT INTO @ProductCentre SELECT 001,'Delhi' 
INSERT INTO @ProductCentre SELECT 002,'Mumbai' 
INSERT INTO @ProductCentre SELECT 003,'Hyd' 

INSERT INTO @ApplicationType SELECT 11,001,'Busines' 
INSERT INTO @ApplicationType SELECT 12,003,'Engg' 
INSERT INTO @ApplicationType SELECT 13,001,'Soft' 
INSERT INTO @ApplicationType SELECT 14,002,'Science' 

SELECT p.* 
FROM @ProductCentre p INNER JOIN 
     @ApplicationType a ON p.prdcntrId = a.prdcntreid 
PIVOT 
     (COUNT(apptypname) FOR apptypname IN ([Busines], 
                [Engg], 
                [Soft], 
                [Science])) p 
+0

與PIVOT功能不錯。 – 2010-03-07 18:45:10

+0

我同意。我昨天剛剛審查了PIVOT。 – 2010-03-07 18:49:17

2

如果`apptypname」類型固定的,那麼這可以工作:

select 
c.prdcntrname, 
Busines = (select count(*) 
      from ApplicationType at 
      where at.prdcntreid = c.prdcntreid and apptypname = 'Business'), 
Engg = (select count(*) 
      from ApplicationType at 
      where at.prdcntreid = c.prdcntreid and apptypname = 'Engg'), 
Soft = (select count(*) 
      from ApplicationType at 
      where at.prdcntreid = c.prdcntreid and apptypname = 'Soft'), 
Science = (select count(*) 
      from ApplicationType at 
      where at.prdcntreid = c.prdcntreid and apptypname = 'Science'), 

from ProductCentre c 
order by c.prdcntrname