I am trying to write a query that will output the following table:
|Day_0_Revenue|Day_1_Revenue|Day_2_Revenue|....|Day_90_Revenue|
The data looks like the following table. Each day will have multiple values, and I want to sum the revenue for each day. Day 0 is 11/1.
|Date|Revenue|
11/1 5
11/2 3
11/3 5
11/3 7
11/4 8
11/5 8
11/5 12
11/6 7
I believe this is simple to do if the table I want is vertical. The reason I want to output horizontally is because I will fill the table vertically with other dates. My main question is how to increment the day value without writing a really long SELECT clause? I'm not sure if I can write a loop that will have something like Day+1 until Day=90...
This is not possible in SQLite alone.
The easiest way would be to just use GROUP BY day to create a vertically oriented table, and then reorder the cells when you are displaying them.
If you really must get a horizontally oriented table from the database, you have to create the query dynamically:
SELECT (SELECT SUM(Revenue) FROM MyTable WHERE Date = '11/1') AS Day_0_Revenue,
(SELECT SUM(Revenue) FROM MyTable WHERE Date = '11/2') AS Day_1_Revenue,
(SELECT SUM(Revenue) FROM MyTable WHERE Date = '11/3') AS Day_2_Revenue,
...
You have to do this in whatever programming language you are using to access the database:
sql = "SELECT"
for i in range(90):
sql += " (SELECT SUM(Revenue) FROM MyTable" +
" WHERE Date = '%s') AS Day_%d_Revenue," % (dates[i], i)
sql = sql[:-1] # remove last comma
cursor = db.execute(sql)
Related
i'm looking for a way to, on my query, dynamically set the beginning of the window function on Sql Server using ROWS BETWEEN.
Something like:
SUM(field) OVER(ORDER BY field2 ROWS BETWEEN field3 PRECEDING AND CURRENT ROW)
field3 holds the amount of items (via group by from a CTE) that represent a group.
Is that possible or should i try a different approach?
>> EDIT
My query is too big and messy to share here, but let me try to explain what i need. It's from a report builder which allows users to create custom formulas, like "emplyoees/10". This also allows the user to simply input a formula like "12" and i need to calculate subtotals and the grand total for them. When using a field, like "employees", everything works fine. But for constant values i can't sum the values without rewriting a lot of stuff (which i'm trying to avoid).
So, consider a CTE called "aggregator" and the following query:
SELECT
*,
"employees"/10 as "ten_percent"
12 as "twelve"
FROM aggregator
This query returns this output:
row_type counter company_name department_name employees ten_percent twelve
data 1 A A1 10 1 12
data 1 A A2 15 1,5 12
data 1 A A3 10 1 12
subtotal 3 A 35 3,5 12
data 1 B B1 10 1 12
subtotal 1 B 10 1 12
total 4 45 4,5 12
As you can see, the values fot "twelve" are wrong for subtotal and total row types. I'm trying to solve this without changing the CTE.
ROLLUP won't work because i already have the sum for other columns.
I tried this (i ommited "row_type_sort" on the table above, it defines the sorting):
CASE
WHEN row_type = 'data' THEN
MAX(aggregator.[twelve])
ELSE
SUM(SUM(aggregator.[twelve]))
OVER (ORDER BY "row_type_sort" ROWS BETWEEN unbounded PRECEDING AND CURRENT ROW)
END AS "twelve"
This would work OK if i could change "unbounded" by the value of column "counter", which was my original question.
LAG/LEAD wasn't helpful neither.
I'm out of ideas. Is it possible to achieve what i need only by changing this part of the query, or the result of the CTE should be changed as well?
Thanks
I just joined after having a problem writing a query in MS Access. I am trying to write a query that will pull out the first two valid samples in from a list of replicated sample results and then would like to average the sample values. I have written a query that does pull samples with only two valid samples and averages these values. However, my query doesn't pull samples where there are more than two valid sample results. Here's my query:
SELECT temp_platevalid_table.samp_name AS samp_name, avg (temp_platevalid_table.mean_conc) AS fin_avg, count(temp_platevalid_table.samp_valid) AS sample_count
FROM Temp_PlateValid_table
WHERE (Temp_PlateValid_table.id In (SELECT TOP 2 S.id
FROM Temp_PlateValid_table as S
WHERE S.samp_name = S.samp_name and s.samp_valid=1 and S.samp_valid=1
ORDER BY ID))
GROUP BY Temp_PlateValid_table.samp_name
HAVING ((Count(Temp_PlateValid_table.samp_valid))=2)
ORDER BY Temp_PlateValid_table.samp_name;
Here's an example of what I'm trying to do:
ID Samp_Name Samp_Valid Mean_Conc
1 54d2d2 1 15
2 54d2d2 1 20
3 54d2d2 1 25
The average mean_conc should be 17.5, however, with my current query, I wouldn't receive a value at all for 54d2d2. Is there a way to tweak my query so that I get a value for samples that have more than two valid values? Please note that I'm using MS Access, so I don't think I can use fancier SQL code (partition by, etc.).
Thanks in advance for your help!
Is this what you want?
select pv.samp_name, avg(pv.value_conc)
from Temp_PlateValid_table pv
where pv.samp_valid = 1 and
pv.id in (select top 2 id
from Temp_PlateValid_table as pv2
where pv2.samp_name = pv.samp_name and pv2.samp_valid = 1
)
group by pv.samp_name;
You might need avg(pv.value_conc * 1.0).
I am using SQL Server 2012 and I have a query which returns two columns, the Item number and the Row number of that item in the query:
Row Item
--------------
1 1234
2 5632
3 4213
4 0912
Before I run the query I will know that I am only interested in the row containing Item 5632 and X number of rows following the one containing item 5632 (in this case lets just say rows 2 and 3). However, I will not know ahead of time what row Item 5632 is in.
I would like to somehow say
Where Row >= Row of Item 5632
And Row <= Row of Item 5632 + X
Is this possible to do? Thank you all!
Supposing the query you have now is SELECT RowNo, Item FROM Tbl, the following query can replace it and do what you want:
DECLARE #Item = 5632
DECLARE #ItemRowNo = SELECT RowNo FROM Tbl WHERE Item = #Item
DECLARE #Qty = 2
SELECT RowNo, Item
FROM Tbl
WHERE Item >= #ItemRowNo
AND Item < (#ItemRowNo + #Qty)
ORDER BY RowNo
If you give me your actual current query, I can update this answer to reflect it.
You may choose to declare less things than what I did if they will be constant, but I'm guessing that you will in fact be SELECTing them from elsewhere.
More than one way to do this, im more accustomed to nested queries
Nested select statement in SQL Server
SQL nested query in SQL server
More specifically:
SELECT TOP 3 a.row, a.item FROM tableA a
WHERE a.row >= (SELECT row FROM tableA WHERE item = 5632)
ORDER BY a.row
TOP doesnt worry about actual value of ROW, just limits number of retrieved records
http://www.w3schools.com/sql/sql_top.asp
http://www.w3schools.com/sql/sql_where.asp
http://www.w3schools.com/sql/sql_orderby.asp
I'm having a problem getting a table to update and am hoping that maybe someone here can help me out. I'm just learning SQL, so I'm not sure of the best way to do certain processes. I have a value in one of my tables that somehow got out of whack. Now, I need to update it using the original value minus the sum of values in a different table.
Table 1 is ORDER_LINES.
ORDER_NO QTY_ON_ORD ORIG_ORD_QTY
0900476 10 100
Table 2 is INVOICED_LINES.
INV_NO SHIP_QTY ORIG_ORD_NO
000441 20 0900476
000441 25 0900476
000441 15 0900476
000441 10 0900476
Value of ORDER_LINES.QTY_ON_ORD should be:
ORDER_LINES.QTY_ON_ORD =
ORDER_LINES.ORIG_ORD_QTY - SUM(INVOICED_LINES.SHIP_QTY)
WHERE INVOICED_LINES.ORIG_ORD_NO = ORDER_LINES.ORDER_NO
So, the value of ORDER_LINES.QTY_ON_ORD is not correct. The values in these are constantly changing, so I'd like to have a SQL command that I can run to update these on the fly. I've tried many things such as:
UPDATE "ORDER_LINES"
SET QTY_ON_ORD = SELECT (
(SELECT SUM(ORIG_ORD_QTY) FROM "ORDER_LINES" WHERE ORDER_NO = '0900476') -
(SELECT SUM(SHIP_QTY) FROM "INVOICED_LINES" WHERE ORIG_ORD_NO = '0900476')
)
WHERE ORDER_NO = '0900476';
But that doesn't work. The Selects by themselves print out the correct qty in my query, but I can't seem to use that qty in my update.
We're running Pervasive SQL if that makes any difference.
I have a process that needs to select rows from a Table (queued items) each row has a quantity column and I need to select rows where the quantities add to a specific multiple. The mulitple is the order of between around 4, 8, 10 (but could in theory be any multiple. (odd or even)
Any suggestions on how to select rows where the sum of a field is of a specified multiple?
My first thought would be to use some kind of MOD function which I believe in SQL server is the % sign. So the criteria would be something like this
WHERE MyField % 4 = 0 OR MyField % 8 = 0
It might not be that fast so another way might be to make a temp table containing say 100 values of the X times table (where X is the multiple you are looking for) and join on that