对多行求和(包括重复项)

时间:2019-09-11 22:13:53

标签: mysql sql

我想获得多种产品的总和/量(其中一种产品可能使用不止一次)

我希望将此作为SQL查询运行,以加快我的PHP脚本的其他方面

这是我正在运行的查询:

void CPCSampleView::OnDisplayReportList ()
{
    CPCSampleDoc *pDoc = GetDocument();

    CDialogDlg myDialog(IDD_DIALOG_REPORTLIST, pDoc, this, [](CDataExchange* pDX, CDocument *pDoc) {
        if (pDX->m_bSaveAndValidate) {
        }
        else {
            CPCSampleDoc *pDocDoc = static_cast<CPCSampleDoc *>(pDoc);
            POSITION pos = NULL;

            do {
                CPCSampleDoc::ListReportList sectionHeader;
                CListBox *x = static_cast<CListBox *>(pDX->m_pDlgWnd->GetDlgItem(IDC_LIST1));

                pos = pDocDoc->GetReportSectionHeader(pos, sectionHeader);
                x->AddString(sectionHeader.m_SectionTitle);
            } while (pos);
        }
    });

    myDialog.SetOnOkCallBack([](CWnd *dlgWnd, CDocument *pDoc) {
        CPCSampleDoc *pDocDoc = static_cast<CPCSampleDoc *>(pDoc);
        CListBox *x = static_cast<CListBox *>(dlgWnd->GetDlgItem(IDC_LIST1));
        int iPtr = x->GetCurSel();
        POSITION pos = NULL;

        do {
            CPCSampleDoc::ListReportList sectionHeader;

            pos = pDocDoc->GetReportSectionHeader(pos, sectionHeader);
            if (iPtr < 1) {
                pDocDoc->MoveToReportSectionHeader(sectionHeader.m_ListOffset);
                break;
            }
            iPtr--;
        } while (pos);
    });

    myDialog.DoModal();
}

此刻,我得到了A2,A1和A3的总和。我希望它也再次向其中添加A1。

2 个答案:

答案 0 :(得分:0)

使用派生表定义值:

select sum(dev.vol)
from (select 'A2' as name union all
      select 'A1' as name union all
      select 'A3' as name union all
      select 'A1' as name
     ) n join
     dev
     using (name)

答案 1 :(得分:0)

您可以使用case..when语法将其乘以2:

select sum( case when `name` = 'A1' then `vol` * 2 else `vol` end ) 
  from dev 
 where `name` in ('A1','A2','A3')