QUERY using cell contents as SQL variables

后端 未结 1 1364
暗喜
暗喜 2021-02-10 05:22

Here is what the spreadsheet I\'m working with looks like:

Summary table

(top of sheet)

\"screens

相关标签:
1条回答
  • 2021-02-10 05:47
    1. Instead of fixed strings such as 'ENQ', you can have your formula refer to the index in column A of your output. For example, you could change your formula to this, in cell C4:

      =QUERY($A$24:$D, "Select D Where B='" & $A4 & "' and A='2/27/14 - Thu'")
                                               ^^^^^^^
      

      The ampersand (&) is used to concatenate string segments.

      Note that since the source data extends to the bottom of the data range of the sheet, we can forego specifying the bottom row. The range $A$24:$D will take in all rows, so it will automatically adjust to additional source data.

    2. To compare dates, both values need to be dates. "2/27/14 - Thu" is not recognized as a date in your source data sheet, but as text, even though you've set the numeric format to date. So make sure you change all your source data to have actual dates in column A.

      You can still have your dates formatted the way you like - see this screenshot. The content of A2 is now a proper date, "2/27/2014", but the format is set to display "mm/dd/yy - DDD". As long as the data is a date, the query can be built using the spreadsheet TEXT function to interpret the date in its yyyy-mm-dd format.

      screenshot

    3. With dates in your source column, you can use todate() scalar function to tell QUERY to convert the date in the source to a query-date, and the date keyword to treat the following literal string (from C2) as a date.

      The resulting function for cell C4 is:

      =QUERY($A$24:$D , "Select D Where B='" & $A4 & "'and todate(A) = date '" & TEXT($C$2,"yyyy-MM-dd") & "'")
                                                              ^^^^^^      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      

      Similarly, for D4:

      =QUERY($A$24:$D , "Select C Where B='"&$A4&"'and todate(A) = date '"&TEXT($C$2,"yyyy-MM-dd")&"'")
      
    4. Your calculations in column E can be improved to handle #N/A results appearing in columns C or D:

      =if(isna(C12*D12),0,C12*D12)
      
    0 讨论(0)
提交回复
热议问题