从database2获取行的值以加入database1

时间:2016-06-17 09:04:12

标签: sql sql-server tsql

需要将TCOUNT包含在我的表中,该表按日期分组,在此查询中,TCOUNT在每行上显示相同的值,这不是我希望显示的。如何让tcount根据分组日期显示特定值

SELECT a.PostingDate,a.Net,a.GROSS,a.DISCS,
    (
      SELECT count(DISTINCT checkno) AS TCOUNT
       FROM [10.0.0.165].[MenuEngg].[dbo].GNDSale
       WHERE dob BETWEEN '2016-01-01 00:00:00' AND '2016-01-30 00:00:00'
         AND branchcode IN ('037')
         AND type IN ('31','19') 
    ) as TCOUNT
FROM
  ( SELECT REPLACE(CONVERT(VARCHAR(20), 
        CAST(abs(SUM( CASE WHEN [G_L Account No_] IN ('5010', '5011','5020','5030')
            AND [Global Dimension 1 Code] = 'BANQUITO' THEN Amount ELSE 0 END)+ 
                  SUM( CASE WHEN [G_L Account No_] BETWEEN '5041' AND '5047'
            AND [Global Dimension 1 Code] = 'BANQUITO' THEN Amount ELSE 0 END)) AS MONEY),1),'.00','') AS Net,
REPLACE(CONVERT(VARCHAR(20),CAST(abs(SUM(CASE WHEN [G_L Account No_] IN ('5010', '5011','5020','5030')
            AND [Global Dimension 1 Code] = 'BANQUITO' THEN Amount ELSE 0 END)) AS MONEY),1),'.00','')as GROSS,
REPLACE(CONVERT(VARCHAR(20),CAST(abs(SUM( CASE WHEN [G_L Account No_] BETWEEN '5041' AND '5047'
            AND [Global Dimension 1 Code] = 'BANQUITO' THEN Amount ELSE 0 END)) AS MONEY),1),'.00','')as DISCS,
           replace(convert(NVARCHAR,[Posting Date],110),'-','/') AS PostingDate
   FROM [The Cravings Group 2013$G_L Entry]
   WHERE [Posting Date] BETWEEN '2016-01-01 00:00:00' AND '2016-01-30 00:00:00'
   GROUP BY [Posting Date] 
   ) a

1 个答案:

答案 0 :(得分:0)

这样写:

...
(
  SELECT count(DISTINCT checkno) AS TCOUNT
   FROM [10.0.0.165].[MenuEngg].[dbo].GNDSale
   WHERE dob BETWEEN '2016-01-01 00:00:00' AND '2016-01-30 00:00:00'
     AND branchcode IN ('037')
     AND type IN ('31','19') 
     --add this
     AND dob = a.[Posting Date]
) as TCOUNT
FROM
  ( SELECT [Posting Date] 
...