2011-06-07 54 views
2

我有一組我想建立從視圖表,例如:我如何返回第一個值的連接表與彙總列

會員

 
ID ¦ Name 
---¦------ 
1 ¦ John 

交易

 
ID¦ MemberID 
--¦----------- 
1 ¦ 1 

TransactionPart

 
ID ¦ TransactionID ¦ SchemeID ¦ Value 
---¦---------------¦----------¦------- 
1 ¦  1  ¦ 1  ¦ 150 
2 ¦  1  ¦ 2  ¦ 50 

方案

 
ID ¦ EmailAddress 
---¦-------------- 
1 ¦ [email protected] 
2 ¦ [email protected] 

典型的行中的視圖將包含部件,交易的總價值和該交易的部分涉及方案中的一個的任何電子郵件地址的名稱。

例如:

 
Name ¦ TotalValue ¦ Email Address 
-----¦------------¦--------------- 
John ¦ 200  ¦ [email protected] 

我想出了低於此statment但如果電子郵件地址不同,它返回2個獨立的行。

 
SELECT 
    m.Name as Name, SUM(tp.Value) as TotalValue, s.EmailAddress as EmailAddress 
FROM 
    Member m INNER JOIN 
    Transaction t ON m.ID = t.MemberID INNER JOIN 
    TransactionPart tp ON tp.TransactionID = t.ID INNER JOIN 
    Scheme s ON s.ID = tp.SchemeID 
GROUP BY 
    m.Name, s.EmailAddress 

結果:

 
Name ¦ TotalValue ¦ Email Address 
-----¦------------¦--------------- 
John ¦ 150  ¦ [email protected] 
John ¦ 50  ¦ [email protected] 

如何返回一個單獨的一行中包含的任何電子郵件地址(可能只是第一個發現)與聚合值總?這是可能的給出的例子顯示?

在此先感謝您的任何意見/答案!

+1

隨意給予好評的答案;) – MatBailie 2011-06-07 13:13:17

+0

我不能與這樣一個低信譽:( – Brett 2011-06-07 13:15:34

回答

1

你幾乎在那裏,所需要的就是上的不是組。

使用任何聚合函數返回a EmailAddress。 (我用MIN

SQL語句

SELECT m.Name as Name 
     , SUM(tp.Value) as TotalValue 
     , MIN(s.EmailAddress) as EmailAddress 
FROM  Member m 
     INNER JOIN Transaction t ON m.ID = t.MemberID 
     INNER JOIN TransactionPart tp ON tp.TransactionID = t.ID 
     INNER JOIN Scheme s ON s.ID = tp.SchemeID 
GROUP BY 
     m.Name 
+0

非常感謝 – Brett 2011-06-07 13:12:26

1

集團僅通過m.Name &上s.EmailAddress申請MAX(或MIN),會給你一個地址( '最大' 與字符串按字母排序):

SELECT 
    m.Name as Name, 
    SUM(tp.Value) as TotalValue, 
    MAX(s.EmailAddress) as EmailAddress 
FROM 
    Member m INNER JOIN 
    Transaction t ON m.ID = t.MemberID INNER JOIN 
    TransactionPart tp ON tp.TransactionID = t.ID INNER JOIN 
    Scheme s ON s.ID = tp.SchemeID 
GROUP BY 
    m.Name 
+0

非常感謝 – Brett 2011-06-07 13:11:59

1

我沒有SQL 2008在我面前,但你可以做一個MIN上一個varchar f ield?

SELECT 
    m.Name as Name, SUM(tp.Value) as TotalValue, MIN(s.EmailAddress) as EmailAddress 
FROM 
    Member m INNER JOIN 
    Transaction t ON m.ID = t.MemberID INNER JOIN 
    TransactionPart tp ON tp.TransactionID = t.ID INNER JOIN 
    Scheme s ON s.ID = tp.SchemeID 
GROUP BY 
    m.Name 


另一種方法是在SchemeID執行一些邏輯,然後使用相關子查詢來獲取電子郵件地址...

SELECT 
    m.Name as Name, 
    SUM(tp.Value) as TotalValue, 
    (SELECT EmailAddress FROM Scheme WHERE ID = MIN(tp.SchemeID)) as EmailAddress 
FROM 
    Member m INNER JOIN 
    Transaction t ON m.ID = t.MemberID INNER JOIN 
    TransactionPart tp ON tp.TransactionID = t.ID 
GROUP BY 
    m.Name 
+0

非常感謝!!! – Brett 2011-06-07 13:12:06

相關問題