2013-03-22 112 views
-3

我工作的SQL查詢,請請給我解決SQL內部聯接查詢

請找有關於申請

數據,如表

表1 'tbl_SuperAdmin'的波紋管任務簡要細節具有例如

s_id name age gtc....... 
1  abc 23 ......... 
2  cda 42 .......... 

另一個表2 'tbl_Renewal'

renewalid renname date supid Payed etc...... 
1   first -  1  1 ........ 
2   first -  2  1 ........ 
3   second -  1  0  ........ 
4   second -  1  1  ........ 
5   third-  1  1  ........ 

查詢select *from tbl_superadmin as a inner join tbl_Renewal as b on a.s_id=b.supid

結果是

s_id name age gtc....... renewalid renname date supid Payed etc....... 
1  abc 23 .............1  first  -  1   1 ........ 
2  cda 42 .............2  first  -  2   1 ........ 
1  abc 23 .............3  second  -  1  0  ........ 
1  abc 23 .............4  second  -  1  1  ........ 
1  abc 23 .............5  third  -  1  1  ........ 

在這裏,我想是如何祈禱,= 1和renewalid遞減,且無需S_ID不重複的1以上的一次

我想顯示我的結果,如

s_id name age gtc....... renewalid renname date supid Payed etc....... 
    1  abc 23 .............5  third  -  1  1  ........ 
    2  cda 42 .............2  first  -  2   1 ........ 

這樣的結果,我想請任何機構幫助它

感謝 普拉迪普

+0

那你試試,在哪裏不是工作? StackOverflow並不意味着「請爲我寫代碼!」地方,但作爲一個你可以學習的地方。請爲我們添加自己的代碼,以便查看:-) – Josien 2013-03-22 11:16:03

+0

如果您提供明確的表結構(而不​​僅僅是數據示例),它也將有所幫助。您可以點擊底部的_edit_按鈕來編輯自己的問題! – Josien 2013-03-22 11:17:00

回答

1

要刪除重複項,您需要使用Windows Function

With cte as 
(
select *,row_number() over(partition by s_id order by renewalid desc)rn 
from tbl_superadmin as a 
inner join tbl_Renewal as b 
on a.s_id=b.supid 
) 
Select * from cte where rn=1 

演示在SQL FIDDLE

更新

;With cte as 
( 
select *,row_number() over(partition by s_id order by renewalid desc)rn 
from alz_SuperAdmin as a inner join alz_Renewal as b on a.s_id=b.supid 
) 
select top 2 CONVERT(varchar(6),a.lastdate,6) as lastdate, 
(select name from alz_states where ID=a.joblocation) as locat, 
from alz_jobpost as a 
inner join 
(Select col1,col2,col3.... from cte where rn=1)ct 
on ct.commonColumn=a.CommonColumn and 
ct.Product in 
(Select query) 
+0

Hai praveen也看到這個問題............................. select top 2 CONVERT(varchar(6),a.lastdate, 6)as lastdate,(選擇alz_states,其中ID = a.joblocation)作爲locat,*從alz_jobpost作爲內部聯接(cte as alz_SuperAdmin作爲內部連接alz_Renewal作爲b上的a.s_id = b.supid)從cte中選擇*,其中rn = 1和cte.product in(從alz_features中選擇[plan],其中Fjobs = 1)和c.Payed = 1)as aa on a.oid = aa.businessid – 2013-03-22 12:13:45

+0

查詢似乎不正確。您不能在'sub query'中使用'CTE' – praveen 2013-03-22 12:17:15

+0

不錯,如果我們可以使用比inner語句更多的內部連接,那麼結果是什麼顯示 – 2013-03-22 12:19:12

0

您應在查詢中使用GROUP BY和ORDER。類似這樣的:

SELECT 
    * 
FROM 
    tbl_SuperAdmin AS a 
INNER JOIN 
    tbl_Renewal AS b 
ON 
    a.s_id = b.supid 
GROUP BY 
    a.s_id 
ORDER BY 
    b.renewalid 
DESC 
+0

這一個顯示此錯誤列'tbl_SuperAdmin.S_id'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 – 2013-03-22 11:02:54

+0

你在分組什麼? – DMK 2013-03-22 11:06:39