复杂的t-sql到linq查询:内连接,分组依据,选择

时间:2015-02-11 13:06:36

标签: linq

我正在尝试基于此构建一个linq查询:

select 
    SERVICE_REQUEST_CR.SRCR_FK_SR, SERVICE_REQUEST.SR_TX_NAME, 
    AC_USER.USER_TX_NAME, SERVICE_REQUEST_CR.SRCR_DT_CREATED,
    SERVICE_REQUEST_CR_STATUS.SRCRST_TX_DESCRIPTION, 
    COUNT(SERVICE_REQUEST_PROGRAM.SRPG_FK_SR_ID) as Activities
from 
    SERVICE_REQUEST_CR
inner join 
    AC_USER on AC_USER.USER_ID = SERVICE_REQUEST_CR.SRCR_FK_REQUESTOR 
inner join 
    SERVICE_REQUEST_CR_STATUS on SERVICE_REQUEST_CR_STATUS.SRCRST_ID = SERVICE_REQUEST_CR.SRCR_FK_CR_STATUS 
inner join 
    SERVICE_REQUEST on SERVICE_REQUEST.SR_ID = SERVICE_REQUEST_CR.SRCR_FK_SR 
inner join 
    SERVICE_REQUEST_PROGRAM on SERVICE_REQUEST_PROGRAM.SRPG_FK_SR_ID = SERVICE_REQUEST_CR.SRCR_FK_SR 
group by 
    SERVICE_REQUEST_CR.SRCR_FK_SR, SERVICE_REQUEST.SR_TX_NAME, 
    AC_USER.USER_TX_NAME, SERVICE_REQUEST_CR.SRCR_DT_CREATED,
    SERVICE_REQUEST_CR_STATUS.SRCRST_TX_DESCRIPTION, 
    SERVICE_REQUEST_PROGRAM.SRPG_FK_SR_ID

这是我能想到的:

Dim x = From cr In db.SERVICE_REQUEST_CR
        Join usr In db.AC_USER On usr.USER_ID Equals cr.SRCR_FK_REQUESTOR
        Join crSt In db.SERVICE_REQUEST_CR_STATUS On crSt.SRCRST_ID Equals cr.SRCR_FK_CR_STATUS
        Join sr In db.SERVICE_REQUEST On sr.SR_ID Equals cr.SRCR_FK_SR
        Join srProg In db.SERVICE_REQUEST_PROGRAM On srProg.SRPG_FK_SR_ID Equals cr.SRCR_FK_SR

有人能帮我一个忙吗?这是令人困惑的分组,所以我只是把连接和查询保持简单。

谢谢,

1 个答案:

答案 0 :(得分:0)

像这样,但我不确定Basic语法:

Dim x = From cr In db.SERVICE_REQUEST_CR
        Join usr In db.AC_USER On usr.USER_ID Equals cr.SRCR_FK_REQUESTOR
        Join crSt In db.SERVICE_REQUEST_CR_STATUS On crSt.SRCRST_ID Equals cr.SRCR_FK_CR_STATUS
        Join sr In db.SERVICE_REQUEST On sr.SR_ID Equals cr.SRCR_FK_SR
        Join srProg In db.SERVICE_REQUEST_PROGRAM On srProg.SRPG_FK_SR_ID Equals cr.SRCR_FK_SR
group new
{
    cr.SRCR_FK_SR, 
    sr.SR_TX_NAME, 
    usr.USER_TX_NAME, 
    cr.SRCR_DT_CREATED,
    crSt.SRCRST_TX_DESCRIPTION, 
    srProg.SRPG_FK_SR_ID
}
by new
{
    cr.SRCR_FK_SR, 
    sr.SR_TX_NAME, 
    usr.USER_TX_NAME, 
    cr.SRCR_DT_CREATED,
    crSt.SRCRST_TX_DESCRIPTION, 
    srProg.SRPG_FK_SR_ID
} into gr
select new
{
    gr.Key.SRCR_FK_SR, 
    gr.Key.SR_TX_NAME, 
    gr.Key.USER_TX_NAME, 
    gr.Key.SRCR_DT_CREATED,
    gr.Key.SRCRST_TX_DESCRIPTION, 
    gr.Key.SRPG_FK_SR_ID,
    Activities = gr.Count()
}