无交易提取帐户

时间:2015-11-04 06:43:06

标签: sql sql-server-2008

我有这张桌子

表1

  

AccountID TrackNumber TransactionDate
  MNL001 10001      20151101
MNL002   10002   20151102个
  MNL003 10003      20151103
MNL004   10004   20151102个
  MNL005 10005      20151101
MNL006   10006   20151101个
  MNL007 10007      20151103
MNL008   10008   20151102个
  MNL009 10009      20151101
MNL010   10010   20151103个

我希望得到那些没有交易的AccountID。

输出应该是:

  

TransationDate AccountID
  20151101   MNL002
20151101   MNL003
  20151101   MNL004
20151101   MNL007
  20151101   MNL008
20151101   MNL010
  20151102   MNL001
20151102   MNL003
  20151102   MNL005
20151102   MNL006
  20151102   MNL007
20151102   MNL009
  20151102   MNL010
20151103   MNL001
  20151103   MNL002
20151103   MNL004
  20151103   MNL005
20151103   MNL006
  20151103   MNL008
20151103   MNL009

请帮我在MS SQL 2008中进行此查询。

感谢

这是我的分析

enter image description here

问题是我不知道如何在查询中这样做。

3 个答案:

答案 0 :(得分:1)

您可以使用CROSS APPLY,如下所示:

SELECT DISTINCT A.TransationDate, B.AccountID
FROM Your_Table A
CROSS APPLY (
      SELECT AccountID FROM Your_Table WHERE TransationDate <> A.TransationDate
      ) AS B

答案 1 :(得分:0)

有许多可能的解决方案。 一种解决方案可能是:

Select t.TransactionDate, t.AccountID
From table1 t
Where not exists 
      (select * 
       from table1 t2 
       where 
       t2.AccountID = t1.AccountID
       and t1.TransactionDate =  t2.TransactionDate
       )

答案 2 :(得分:0)

在不同日期和帐户之间执行cross join,并使用left join搜索表格中的非现有值:

DECLARE @t TABLE
    (
      AccountID VARCHAR(10) ,
      TrackNumber VARCHAR(10) ,
      TransactionDate DATE
    )
INSERT  INTO @t
VALUES  ( 'MNL001', '10001', '20151101' ),
        ( 'MNL002', '10002', '20151102' ),
        ( 'MNL003', '10003', '20151103' ),
        ( 'MNL004', '10004', '20151102' ),
        ( 'MNL005', '10005', '20151101' ),
        ( 'MNL006', '10006', '20151101' ),
        ( 'MNL007', '10007', '20151103' ),
        ( 'MNL008', '10008', '20151102' ),
        ( 'MNL009', '10009', '20151101' ),
        ( 'MNL010', '10010', '20151103' )

;WITH distinctAccounts AS(SELECT DISTINCT AccountID FROM @t),
      distinctDates AS(SELECT DISTINCT TransactionDate FROM @t)

SELECT dd.TransactionDate, da.AccountID 
FROM distinctAccounts da
CROSS JOIN distinctDates dd
LEFT JOIN @t t ON t.AccountID = da.AccountID AND t.TransactionDate = dd.TransactionDate
WHERE t.AccountID IS NULL
ORDER BY dd.TransactionDate, da.AccountID

输出:

TransactionDate AccountID
2015-11-01      MNL002
2015-11-01      MNL003
2015-11-01      MNL004
2015-11-01      MNL007
2015-11-01      MNL008
2015-11-01      MNL010
2015-11-02      MNL001
2015-11-02      MNL003
2015-11-02      MNL005
2015-11-02      MNL006
2015-11-02      MNL007
2015-11-02      MNL009
2015-11-02      MNL010
2015-11-03      MNL001
2015-11-03      MNL002
2015-11-03      MNL004
2015-11-03      MNL005
2015-11-03      MNL006
2015-11-03      MNL008
2015-11-03      MNL009
相关问题