将SQL查询中的值除以1024以获得KB大小

时间:2015-05-28 09:29:41

标签: sql sql-server sql-server-2008 tsql division

我按照以下查询提取字节大小:

 SELECT CASE_NUM, 
        CUST_CODE, 
        CUST_NAME, 
       ISNULL(C.[NR OF ATTACHMENTS], 0) 'NR OF ATTACHMENTS', 
       ISNULL(C.[SIZE OF ATTACHMENTS KB], 0) 'SIZE OF ATTACHMENTS KB' 
      FROM CUSTCASE
 LEFT OUTER JOIN (
       SELECT B.CASE_CODE, 
              ISNULL(COUNT(B.ATTACHED_DOC_ID), 0) 'NR OF ATTACHMENTS',  
              ISNULL(SUM(B.DOC_SIZE), 0) 'SIZE OF ATTACHMENTS KB' 
       FROM
       (SELECT CASE_CODE, 
               ATTACHED_DOC_ID, 
               ISNULL(A.DOC_SIZE, 0) 'DOC_SIZE' 
        FROM CONTACT
        LEFT OUTER JOIN (SELECT DOC_ID, 
                                DATALENGTH(DATA) 'DOC_SIZE'
                         FROM ATTACHED_DOCS) A 
       ON CONTACT.ATTACHED_DOC_ID = A.DOC_ID
       WHERE CONTACT.CASE_CODE IS NOT NULL) B
       GROUP BY B.CASE_CODE
    ) C 
    ON CUSTCASE.CASE_CODE = C.CASE_CODE 
    where  ISNULL(C.[NR OF ATTACHMENTS], 0) > 0

要将尺寸设为KB,我需要除以1024,但在这种情况下无法应用它。

2 个答案:

答案 0 :(得分:3)

SELECT CASE_NUM, CUST_CODE, CUST_NAME, ISNULL(C.[NR OF ATTACHMENTS], 0) 'NR OF ATTACHMENTS', CASE WHEN ISNULL(C.[SIZE OF ATTACHMENTS KB], 0) = 0 THEN 0 ELSE C.[SIZE OF ATTACHMENTS KB]/1024) END AS 'SIZE OF ATTACHMENTS KB' 
FROM CUSTCASE
LEFT OUTER JOIN (SELECT B.CASE_CODE, ISNULL(COUNT(B.ATTACHED_DOC_ID), 0) 'NR OF ATTACHMENTS', CASE WHEN ISNULL(SUM(B.DOC_SIZE), 0) = 0 THEN 0 ELSE SUM(B.DOC_SIZE)/1024 END AS  'SIZE OF ATTACHMENTS KB' 
                 FROM (SELECT CASE_CODE, ATTACHED_DOC_ID, ISNULL(A.DOC_SIZE, 0) 'DOC_SIZE' 
                       FROM CONTACT
                       LEFT OUTER JOIN (SELECT DOC_ID, DATALENGTH(DATA) 'DOC_SIZE'
                                        FROM ATTACHED_DOCS) A ON CONTACT.ATTACHED_DOC_ID = A.DOC_ID
                       WHERE CONTACT.CASE_CODE IS NOT NULL) B
                       GROUP BY B.CASE_CODE) C ON CUSTCASE.CASE_CODE = C.CASE_CODE 
WHERE ISNULL(C.[NR OF ATTACHMENTS], 0) > 0

答案 1 :(得分:3)

问题是分隔符的放置不正确:

SELECT CASE_NUM, 
    CUST_CODE, 
    CUST_NAME, 
   ISNULL(C.[NR OF ATTACHMENTS], 0) 'NR OF ATTACHMENTS', 
   ISNULL(C.[SIZE OF ATTACHMENTS KB], 0) 'SIZE OF ATTACHMENTS KB' 
  FROM CUSTCASE
LEFT OUTER JOIN (
   SELECT B.CASE_CODE, 
          ISNULL(COUNT(B.ATTACHED_DOC_ID), 0) 'NR OF ATTACHMENTS',  
          ISNULL(SUM(B.DOC_SIZE), 0) 'SIZE OF ATTACHMENTS KB' 
   FROM
   (SELECT CASE_CODE, 
           ATTACHED_DOC_ID, 
           ISNULL(A.DOC_SIZE, 0) 'DOC_SIZE' 
    FROM CONTACT
    LEFT OUTER JOIN (SELECT DOC_ID, 
                            DATALENGTH(DATA)/1024 'DOC_SIZE'
                     FROM ATTACHED_DOCS) A 
   ON CONTACT.ATTACHED_DOC_ID = A.DOC_ID
   WHERE CONTACT.CASE_CODE IS NOT NULL) B
   GROUP BY B.CASE_CODE
) C 
ON CUSTCASE.CASE_CODE = C.CASE_CODE 
where  ISNULL(C.[NR OF ATTACHMENTS], 0) > 0