0

仅选择唯一发票。

我有下表:


Invoice Date    Invoice No  Description                     PO No           Order No            Amount  Credit  Total
2013-04-26      T641913   PURCH/GRIP/SHOWCARD               LG5582          T196786             314.25      0   314.25
2013-04-26      T641914   PURCH/GRIP/SASH & TAPE            LG5593          T196855             251.20      0   251.20
2013-04-26      T641915   PURCH/LTG/BULB & RECEIVERS        LG5595          T196858             202.59      0   202.59
2013-04-26      T641916   PURCH/GRIP/STYRO & SILENT GRID    LG 5599         T196888             257.81      0   257.81
2013-04-26      T641      MAIN HEAD                         LG 5580         T192282             147725.62   0   147725.62
2013-04-26      T641      MAIN HEAD                         LG 5649         T196707             147725.62   0   147725.62
2013-04-26      T641      MAIN HEAD                         LG 5580         T192279             147725.62   0   147725.62
2013-04-26      T641      MAIN HEAD                         LG 5580         T192280             147725.62   0   147725.62

我需要压缩并且只选择唯一发票#。结果表应如下所示:


Invoice Date    Invoice No  Description                     PO No           Order No            Amount  Credit  Total
2013-04-26      T641913   PURCH/GRIP/SHOWCARD               LG5582          T196786             314.25      0   314.25
2013-04-26      T641914   PURCH/GRIP/SASH & TAPE            LG5593          T196855             251.20      0   251.20
2013-04-26      T641915   PURCH/LTG/BULB & RECEIVERS        LG5595          T196858             202.59      0   202.59
2013-04-26      T641916   PURCH/GRIP/STYRO & SILENT GRID    LG 5599         T196888             257.81      0   257.81
2013-04-26      T641      MAIN HEAD                         MULTI           MULTI               147725.62   0   147725.62

不知道该怎么做:S请帮助!

4

2 回答 2

2
SELECT [Invoice Date],
  [Invoice No],
  Description,
  [PO No] = CASE WHEN COUNT(1) > 1 THEN 'MULTI' ELSE MAX([PO No]) END,
  [Order No] = CASE WHEN COUNT(1) > 1 THEN 'MULTI' ELSE MAX([Order No]) END,
  Amount,
  Credit,
  Total
FROM Invoices
GROUP BY [Invoice Date],
  [Invoice No],
  Description,
  Amount,
  Credit,
  Total

SQL Fiddle 与演示

于 2013-05-06T19:23:28.427 回答
1

这是CTE的答案...

With    cte As
(
        Select  Count(1) As i, 
                [Invoice No],
                'MULTI' As val
        From    [Table]
        Group   By [Invoice No]
        Having  Count(1) > 1
)
Select  Distinct
        t.[Invoice Date],
        t.[Invoice No],
        t.[Description],
        IsNull(c.val,t.[PO No]) As [PO No],
        IsNull(c.val,t.[Order No]) As [Order No],
        t.[Amount],
        t.[Credit],
        t.[Total]
From    [Table] t
Left    Join cte c
        On  t.[Invoice No] = c.[Invoice No]
于 2013-05-06T19:24:42.327 回答