1

我有 4 张桌子。

Procedures

Name   Cost
Proc1  10
Proc2  20
Proc3  30
Proc4  40

MaterialsUsed

NameOfTheProcedure  MaterialUsed  AmountOfMaterialUsed
proc1               mat1              1
proc2               mat2              3
proc3               mat3              2
proc4               mat4              1

Materials

Name   Id   Price
mat1   1    10
mat2   2    20
mat3   3    30
mat4   4    40

ProceduresDone

ClientID   NameOfProcedure  Date
Client1    proc1            2012-11-24
Client2    proc2            2012-11-23
Client3    proc3            2012-11-24
Client4    proc4            2012-11-23

我需要编写一个查询来返回在特定日期完成的程序。它应该有 3 列(NameOfTheProcedure、HowManyTimesThatProcedureWasDoneInThatDay、TotalPrice)。TotalPrice 列包括来自材料表的价格和来自过程一的价格。

是否可以通过单个查询来做到这一点?

编辑:

示例结果应该类似于(日期为 2012-11-24):

NameOfTheProcedure    AmountOfTimesProcedureWasDoneThatDay    TotalPrice
proc1                 1                                       20
proc3                 1                                       90
4

1 回答 1

1

尝试这样的事情,

SELECT  a.NameOfTheProcedure,
        COUNT(a.NameOfTheProcedure) AmountOfTimesProcedureWasDoneThatDay,
        SUM(b.AmountOfMaterialUsed * d.Price) +
        SUM(c.Cost) TotalPrice
FROM    ProceduresDone a
        INNER JOIN MaterialsUsed b
            ON a.NameOfProcedure = b.NameOfTheProcedure
        INNER JOIN Procedures c
            ON c.Name = a.NameOfProcedure
        INNER JOIN Materials d
            ON b.MaterialUsed = d.Name
WHERE   a.Date = '2012-11-24'
于 2012-11-25T13:48:11.667 回答