0

我有一个可怕的问题查询要写

SELECT TOP 25
uinv = (CASE 
    WHEN exported = 1 THEN 'Sent To Accounts' 
    WHEN queued = 1 THEN 'Finalised' 
    WHEN reviewed = 1 THEN 'Pro Forma' 
    WHEN started = 1 THEN 'New' 
END)
,
(
    CAST(acc_id AS VARCHAR) + ' / ' + 
    CAST(transactiontype AS VARCHAR) + ' / ' + 
    CAST(reference AS VARCHAR) + ' / '
) 
AS label 
FROM tablename;

这很好用,但我需要在 AS 标签中获取 uinv 字段。我已经尝试了各种排列,但我就是无法正确...

请问有什么帮助吗?

谢谢,克里斯

4

2 回答 2

1

你的意思是这样吗?:

SELECT
    tbl.uinv,
    (
        tbl.uinv+
        CAST(acc_id AS VARCHAR) + ' / ' + 
        CAST(transactiontype AS VARCHAR) + ' / ' + 
        CAST(reference AS VARCHAR) + ' / '
    ) 
    AS label 
FROM
(
    SELECT TOP 25
    uinv = (CASE 
        WHEN exported = 1 THEN 'Sent To Accounts' 
        WHEN queued = 1 THEN 'Finalised' 
        WHEN reviewed = 1 THEN 'Pro Forma' 
        WHEN started = 1 THEN 'New' 
    END),
    tablename.acc_id,
    tablename.transactiontype,
    tablename.reference
    FROM tablename
) AS tbl
于 2013-06-11T08:56:46.487 回答
1

如果您只想将 uinv 放在里面而不是单独的列,那么您需要做的就是将机箱移到里面;

SELECT TOP 25
(
    CAST(acc_id AS VARCHAR) + ' / ' + 
    CAST(transactiontype AS VARCHAR) + ' / ' + 
    CAST(reference AS VARCHAR) + ' / ' + 
    CASE 
      WHEN exported = 1 THEN 'Sent To Accounts' 
      WHEN queued = 1 THEN 'Finalised' 
      WHEN reviewed = 1 THEN 'Pro Forma' 
      WHEN started = 1 THEN 'New' 
    END
) 
AS label 
FROM tablename;

如果除了作为单独的列之外,还希望它在标签内,则可以使用 CTE;

WITH cte AS (
  SELECT *,CASE 
      WHEN exported = 1 THEN 'Sent To Accounts' 
      WHEN queued = 1 THEN 'Finalised' 
      WHEN reviewed = 1 THEN 'Pro Forma' 
      WHEN started = 1 THEN 'New' 
    END uinv
  FROM tablename
)
SELECT uinv,  
    CAST(acc_id AS VARCHAR) + ' / ' + 
    CAST(transactiontype AS VARCHAR) + ' / ' + 
    CAST(reference AS VARCHAR) + ' / ' + 
    uinv
AS label 
FROM cte;
于 2013-06-11T09:01:15.377 回答