SELECT 使用相关子查询和多个表

SELECT using Correlated Sub Queries and multiple tables

我有两个 table(表 1 和表 2)。一个包括一个日期 (tDate) 列和一个我想作为分组依据的 ID (tTillNo) 列。另一个具有我想为每个日期和 ID 求和的值 (pValue)。

可以使用每个 table 中的 'tName' 和 'pName' 列连接 table,但是 pName 列可能有重复项,我想计入总和。 对于 3 个子查询,我还需要使用 'pCode' 列包含 where 子句。

我想 return 此处显示的列

然而,使用下面的代码 returns 子查询的总计不正确,因为我正在使用 'MAX(a.tName)' 来防止对该字段进行分组。谁能建议另一种方法来防止这种情况或进行此查询的另一种方法?

SELECT 
    DATENAME(Month,a.tDate) as 'Month Name', DAY(a.tDate) as 'Day', 
    MONTH(a.tDate) as 'Month', YEAR(a.tDate) as 'Year', a.tTillNo,

    BankedCash=(SELECT ISNULL(CAST(SUM(b.pValue) as numeric(12,2)),0) 
               FROM Table2 b 
                    where MAX(a.tName)=b.pName AND pCode = 'CSH' 
                    or pCode = 'CHQ'),

    CardTransactions=(SELECT ISNULL(CAST(SUM(b.pValue) as numeric(12,2)),0) 
                     FROM Table2 b 
                          where MAX(a.tName)=b.pName AND b.pCode = 'CRD'),

    BankingTotal=(SELECT ISNULL(CAST(SUM(b.pValue) as numeric(12,2)),0) 
                 FROM Table2 b 
                      where MAX(a.tName)=b.pName AND b.pCode = 'CSH' or 
                      b.pCode = 'CHQ' or b.pCode = 'CRD')

FROM Table1 a

group by YEAR(a.tDate), MONTH (a.tDate), DATENAME(Month,a.tDate), 
DAY(a.tDate), a.tTillNo

order by YEAR(a.tDate), MONTH (a.tDate), DATENAME(Month,a.tDate)

任何建议或文章推荐将不胜感激。非常感谢。

CREATE TABLE [dbo].[Table1](
[UniqueID] [int] IDENTITY(1,1) NOT NULL,
[tTillNo] [varchar](4) NULL,
[tName] [varchar](20) NULL,
[tDate] [datetime] NULL)

INSERT INTO Table1 (tTillNo, tName, tDate)
VALUES ('0101', '01010000001', '2018-10-30 00:00:00.000'),
       ('0101', '01010000002', '2018-10-30 00:00:00.000'),
       ('0102', '01020000001', '2018-10-30 00:00:00.000'),
       ('0102', '01020000002', '2018-10-30 00:00:00.000')

CREATE TABLE [dbo].[Table2](
[UniqueID] [int] IDENTITY(1,1) NOT NULL,
[pName] [varchar](20) NULL,
[pCode] [varchar](10) NULL,
[pValue] [decimal](22, 7) NULL)


INSERT INTO Table2 (pName, pCode, pValue)
VALUES ('01010000001', 'CRD', '100.0000000'),
       ('01010000002', 'CSH', '100.0000000'),
       ('01020000001', 'CHQ', '100.0000000'),
       ('01020000002', 'CSH', '100.0000000'),
       ('01020000002', 'CRD', '100.0000000'),
       ('01010000001', 'CSH', '100.0000000')

我想你可以通过连接来解决这一切。

select DATENAME(Month,a.tDate) as 'Month Name'
   , DAY(a.tDate) as 'Day'
   , MONTH(a.tDate) as 'Month'
   , YEAR(a.tDate) as 'Year'
   , a.tTillNo
   , BankedCash=SUM(case when pCode in( 'CSH','CHQ') then pvalue else 0 end)
   , [Card] = SUM(case when pCode in( 'CRD') then pvalue else 0 end)
   ,Total = SUM(pvalue)
from TableA a
    join TableB b on a.tName=b.pName
group by YEAR(a.tDate)
    , MONTH (a.tDate)
    , DATENAME(Month,a.tDate)
    , DAY(a.tDate)
    , a.tTillNo