I have a question about adding a row number over 2 queries.
My query is:
SELECT
'telxm001001' AS Node,
'1' AS [Speed Dialing],
'0' AS [Spd DI Numbers by Range],
NULL as 'Speed Dialing No.',
REPLACE(TelefonGeschaeft, '+', '00') AS [Call Number],
Nachname AS [Directory Name],
Vorname AS [Directory First Name]
FROM
dbo.MaData
WHERE
(TelefonGeschaeft LIKE '+%')
UNION ALL
SELECT
'telxm001001' AS Node,
'1' AS [Speed Dialing],
'0' AS [Spd DI Numbers by Range],
ROW_NUMBER() OVER (ORDER BY Nachname) AS 'Speed Dialing No.',
REPLACE(MobiltelefonGeschaeft, '+', '00') AS [Call Number],
Nachname AS [Directory Name],
Vorname AS [Directory First Name]
FROM
dbo.MaData
WHERE
(MobiltelefonGeschaeft LIKE '+%')
I have a SQL Server table with 1400 entries. The 2 queries brings me the right results but the row numbers are not correct because the numerations Begins at 1 when the second query starts. So in my query result i have a numeration from 1 to 680 and then the numeration Begins at 1 when the second query starts. Is there a way to add a row numbering after the two queries finished so the numeration is from 1 to 1400?
Best regards
switzly
Apply a ROW_NUMBER ordering over a derived query; supply a discriminator (e.g. queryOrder) through the individual queries to keep the relevant results grouped.
SELECT ROW_NUMBER() OVER (ORDER BY queryOrder, [Directory Name]) AS number
FROM (
SELECT 1 AS queryOrder, [Directory Name] ..
UNION ALL
SELECT 2 AS queryOrder, [Directory Name] ..
) j
Before jump into too techie in to this query, do you want to have the row number for both the queries?
If yes, why are you putting NULL in the first query?
If you want to have row number for both the queries, use it on both the queries.
Otherwise, try put them into another query as below:
select
ROW_NUMBER over ..., Node, [Speed Dialing], ....
from
(<actual query here>) as temp1;
Related
Feeling a bit confused here, I have a query running against SQL Server where I am trying to return a single row per trans_id and action number (they may be repeated). The trans column would be different in the repeated rows so I only ever want to return the highest (max value) of the trans column to give me the single row per trans_id and action number.
This seems to do the trick:
SELECT DT.trans_id,
MAX(DT.trans),
DA.ACTION_NO,
DT.[Title] AS [Case Title],
DA.[Description] AS [Action Description],
DA.ACTION_TIME_LIMIT AS [Action Deadline],
DA.Performed AS [Action Perfomed]
FROM synergi.stg_D_TRANS DT
INNER JOIN EQDW_Stg.synergi.stg_D_ACTION DA ON DA.TRANS = (SELECT MAX(TRANS)FROM synergi.stg_D_TRANS WHERE trans_id = DT.TRANS_ID)
WHERE DT.TRANS_ID != 0
GROUP BY DT.TRANS_ID,
DA.ACTION_NO,
DT.TITLE,
DA.DESCRIPTION,
DA.PERFORMED,
DA.ACTION_TIME_LIMIT;
However, when I add in this specific column, DT.TRANS_DATE, I get an additional 18 rows because it is returning one of the trans_id with 2 different trans numbers instead of just the rows with the max.
Why would adding in the date column affect this when I have numerous other columns from the same table that adding/removing don't seem to change the result at all.
SELECT DT.trans_id,
MAX(DT.trans),
DA.ACTION_NO,
DT.[Title] AS [Case Title],
DA.[Description] AS [Action Description],
DA.ACTION_TIME_LIMIT AS [Action Deadline],
DA.Performed AS [Action Perfomed],
DT.TRANS_DATE
FROM synergi.stg_D_TRANS DT
INNER JOIN EQDW_Stg.synergi.stg_D_ACTION DA ON DA.TRANS = (SELECT MAX(TRANS)FROM synergi.stg_D_TRANS WHERE trans_id = DT.TRANS_ID)
WHERE DT.TRANS_ID != 0
GROUP BY DT.TRANS_ID,
DA.ACTION_NO,
DT.TITLE,
DA.DESCRIPTION,
DA.PERFORMED,
DA.ACTION_TIME_LIMIT,
DT.TRANS_DATE;
[enter image description here][1]I need to add 4 columns ( Item name, FullPrice_2018(price), FullPrice_2019(price), (FullPrice_2019-FullPrice_2018) ) to the query. I can't figure out how to add another column to the union without merging rows.
Right now my table is with 2018 & 2019 items but I need 3 more columns.
https://i.stack.imgur.com/lTmqB.png
SELECT FullPrice_2018.[Item name]
FROM FullPrice_2018
UNION
SELECT FullPrice_2019.[Item name]
FROM FullPrice_2019
ORDER BY [Item name]
Result should be like this
"Item name" price2018 price2019 "price2019-price2018"
https://i.stack.imgur.com/XxKU5.png
Do you just want JOIN:
SELECT F2018.[Item name], F2018.FullPrice, F2019.FullPrice,
(F2019.FullPrice - F2018.FullPrice)
FROM FullPrice_2018 as F2018 INNER JOIN
FullPrice_2019 as F2019
ON F2018.[Item name] = F2019.[Item name]
ORDER BY F2018.[Item name];
Unfortunately, MS Access doesn't support FULL JOIN. But I think you can do:
SELECT [Item name], MAX(FullPrice_2018), MAX(FullPrice_2019),
(MAX(FullPrice_2019) - MAX(FullPrice_2018))
FROM (SELECT F2018.[Item name], F2018.FullPrice as FullPrice_2018, NULL as FullPrice_2010
FROM FullPrice_2018 as F2018
UNION ALL
SELECT F2019.[Item name], NULL, F2019.FullPrice as FullPrice_2019
FROM FullPrice_2019 as F2019
) F
GROUP BY [Item name]
ORDER BY [Item name];
Not all versions of MS Access support UNION ALL in the FROM clause, so you might need to use a view for that portion of the query.
Create a query that will return a normalised output:
SELECT
FullPrice_2018.[Item name], 2018 As [Year], Price
FROM
FullPrice_2018
UNION ALL
SELECT
FullPrice_2019.[Item name], 2019 As [Year], Price
FROM
FullPrice_2019
Save the query and use it as source in a normal crosstab query. Use the wizard to create this if you are unfamiliar with crosstab queries.
I am trying to add a Sum 'field' to a SELECT query, where it sums up the data on that row, and returns it as a field. The problem seems to lie with the GROUP BY statement, that I seemingly have to use. When using this, it groups the 'sums' together, rather than provides a total for each row of data.
SELECT PS_DB.TeamName AS [Team Name], TM_adjData.SM_adjName AS Adjudicator, PS_DB.WeekEnding AS [Week Ending], PS_DB.Pts AS [BAU Points], PS_DB.Adhc, Sum(PS_DB.Pts + PS_DB.Adhc) as [Total], PS_DB.Approved AS Approved
FROM PS_DB
LEFT JOIN TM_adjData on PS_DB.Adjudicator = TM_adjData.SM_empNum
GROUP BY TeamName, SM_adjName, WeekEnding, Pts, Adhc, Approved
This returns 518 rows, where as if I remove the GROUP BY section and the 'sum' field, it returns 1,608 rows (which is correct).
How can I get the 1,608 rows with the sum next to it?
I think you can do what you want with a correlated subquery:
SELECT p.TeamName AS [Team Name], a.SM_adjName AS Adjudicator,
p.WeekEnding AS [Week Ending], p.Pts AS [BAU Points], p.Adhc,
(SELECT SUM(p2.Pts + p2.Adhc)
FROM PS_DB as p2
WHERE p2.TeamName = p.TeamName -- perhaps more conditions are needed
) as [Total],
p.Approved AS Approved
FROM PS_DB as p LEFT JOIN
TM_adjData as a
ON p.Adjudicator = a.SM_empNum;
If you want to perform a sum for each row, you don't group rows, instead you simply perform addition. I've added Nz() function to properly address issue where any of the value being added is null and treat it as 0:
SELECT
PS_DB.TeamName AS [Team Name],
TM_adjData.SM_adjName AS Adjudicator,
PS_DB.WeekEnding AS [Week Ending],
PS_DB.Pts AS [BAU Points],
PS_DB.Adhc,
Nz(PS_DB.Pts,0) + Nz(PS_DB.Adhc,0) as [Total], -- this is your row sum
PS_DB.Approved AS Approved
FROM PS_DB
LEFT JOIN TM_adjData on PS_DB.Adjudicator = TM_adjData.SM_empNum
SUM is an aggregate function and it works on entire table or groups of data (with GROUP BY).
I have a three column table of price breaks called "FPB" that looks like this:
[Part Number] [Quantity] [Price]
AAA-AAAA 100 1.23
AAA-AAAA 200 1.15
BBB-BBBB 100 5.60
CCC-CCCC 500 3.21
....
Where each part number has multiple entries in multiple rows.
I'm trying to reorganize the table to look more like this
[Part Number] [Quantity1] [Price 1] [Quantity 2] [Price 2] [Quantity 3....
AAA-AAAA 100 1.23 200 1.15 ....
BBB-BBBB 100 5.60 ...
CCC-CCCC 500 3.21 ...
...
Where each part number has all its entries combined into one row. The first quantity column should have the lowest available quantity, the second should have the second smallest etc. I am trying to do this by first creating a 1-column table with just the unique part numbers using GROUP BY, and then creating more tables for each column that has the information I want in that column, and then joining it by Part Number. The problem comes when calculating the second smallest quantity for each type, done in the second to last section.
SELECT PNs.[Part Number], Q1T.Q1, P1T.Price, Q2T.Q2
FROM
(SELECT
[Part Number]
FROM FPB
GROUP BY [Part Number]
) AS PNs,
(SELECT
[Part Number],
MIN(Quantity) AS Q1
FROM FPB
GROUP BY [Part Number]
) AS Q1T,
(SELECT
*
FROM FPB
) AS P1T,
(SELECT
[Part Number],
MIN(IIF(Quantity>Q1T.Q1,Quantity)) AS Q2
FROM FPB
GROUP BY [Part Number]
) AS Q2T
WHERE
PNs.[Part Number] = Q1T.[Part Number]
AND P1T.[Part Number] = PNs.[Part Number]
AND P1T.Quantity = Q1T.Q1
AND Q2T.[Part Number] = PNs.[Part Number]
When I run this query, it asks me to enter a parameter value for Q1T.Q1, even though it already exists. If I remove the code section for Q2T, as well as any references to Q2, it will work without a problem, and it won't ask about a value for the other instances of Q1T.Q1. Why doesn't Q1T.Q1 have a value just for that section, and how can I fix it? As a side note, I'm using the SQL features of a program called PHPRunner, and its client doesn't support UPDATE/DELETE/INSERT/CREATE queries, UNION, and DISTINCT.
You're looking for something like this.
select
p1.PartNumber,
ifnull(max(p2.Quantity), 0) + 1 as LowerQuantity,
p1.Quantity as UpperQuantity,
p1.Price,
count(p2.PartNumber) + 1 as PriceTier
from
FPB p1 left outer join FPB p2
on p2.PartNumber = p1.PartNumber and p2.Quantity < p1.Quantity
From there it's easy to pivot in order to insert into a new table:
into into NewFPB (PartNumber, Quantity1, Price1, Quantity2, Price2, ...)
select
PartNumber,
min(switch(PriceTier = 1, UpperQuantity)) as Quantity1,
min(switch(PriceTier = 2, UpperQuantity)) as Quantity2, ...
min(switch(PriceTier = 1, Price)) as Price1,
min(switch(PriceTier = 2, Price)) as Price2, ...
from (
select
p1.PartNumber,
ifnull(max(p2.Quantity), 0) + 1 as LowerQuantity,
p1.Quantity as UpperQuantity,
p1.Price,
count(p2.PartNumber) + 1 as PriceTier
from
FPB p1 left outer join FPB p2
on p2.PartNumber = p1.PartNumber and p2.Quantity < p1.Quantity
) data
You might have to tweak it a little bit for Access to accept it. But the core ideas are there.
The query you call is incorrect.
Q1T is inner select statement , and in Q2T (other inner select statement) , you can't use any field from Q1T
The SQL Server raise error: Incorrect syntax near ')'.
To overcome this limitation , you should use Common Table Expressions CTE
for PNs, Q1T, P1T, Q2T
CTE is like dynamic view.
It's a new feature since sql 2008 and It's a very powerful.
review: https://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx
Try to Draw a relational data model for these four CTE to be sure that a relation exist between them based on your where conditions.
I think the logic in this query may raise runtime error during execution:
e.g. The multi-part identifier "Q1T.Q1" could not be bound.
Edit:
For Ms-Access you can create four queries for: PNs, Q1T, P1T, Q2T every one is in a separate query, and the fifth query join these queries and add where conditions.
In this case you will not get any syntax error. and will get Data model with relation free :) .
As per your question, by the time you define the derived table Q2T, Q1T is still an invalid object. You need to try to work around this issue.
EDIT:
Suppose you only got 2-level columns to handle, the code is listed below, i tested it. It works well.
select q5.*,q3.quantity, q3.price
from
(select *
from FPB as Q1
where 0 = (select count(distinct(quantity)) from FPB as Q2 where Q2.quantity < Q1.quantity AND Q2.[part number] = Q1.[part number])) as Q5
,
(
select distinct(temp.[part number]),Q2.quantity, Q2.price from FPB as temp
left join
(select *
from FPB as Q4
where 1 = (select count(distinct(quantity)) from #test as Q2 where Q2.quantity < Q4.quantity AND Q2.[PART NUMBER] = Q4.[PART NUMBER])) as Q2
on temp.[PART NUMBER] = Q2.[PART NUMBER]
) as Q3
where Q5.[PART NUMBER] = Q3.[PART NUMBER]
In my Access application I join two resultsets with UNION. This worked for years, but now it stopped working, because after the union one text field just shows some crude chinese characters.
This is the setup:
1. select id,fieldA,1 as fieldB from tableA where cond=1
2. select id,"" as fieldA,2 as fieldB from tableA where cond=0
These queries seperately show the correct results. But after I join them with
select * from subquery1 UNION select * from subquery2
the data from fieldA is just some chinese characters like 㼄W. I have no idea where this comes from.
After some trying I found out that the following query shows the correct results:
select * from subquery1 where id=1 UNION select * from subquery2 where id=1
A nice side-effect is the performance improvement, although I have to change the querydef each time. But how come this works and the old version stopped working?
Instead of showing an empty string "", try adding Null
SELECT id, fieldA, 1 as fieldB FROM tableA WHERE cond=1
UNION SELECT id,Null as fieldA,2 as fieldB FROM tableA where cond=0;
For information, I solved a similar issue simply by using UNION ALL, with the side benefit of an improved performance.
The problem is that Access uses the types in the first SELECT statement in a union query to determine the types of the fields in the query. If you use a null value in this first select block, it has no idea what type to use and messes up. The simplest solution is to re-order the select blocks in your query so that the first one does not contain a null entry. Alternatively, the most generic solution is to create a null table with one field of each type you need, but no data in the table :-
Null Values Table
Field Name Data Type
Null Id AutoNumbered
Null Int Number
Null Currency Currency
Null Date Date/time
Null Text Short Text
Then incorporate a dummy SELECT block prior to the first real block that uses the entries from this Null table :-
SELECT
[Null Date] AS [Date],
[Null Id] AS [Index],
[Null Text] AS [Description],
[Null Currency] AS [Income Tax],
[Null Currency] AS [Employers NI],
[Null Currency] AS [Employees NI],
[Null Currency] AS [Amounts Due],
[Null Currency] AS [Payments],
[Null Currency] AS [Balance]
FROM [Null Values Table];
UNION SELECT
[Date],
Int(Null) AS [Index],
"Salary" AS [Description],
[Income Tax],
[Employers NI],
[Employees NI],
[Income Tax] + [Employers NI] + [Employees NI] AS [Amounts Due],
Int(Null) AS [Payments],
[Income Tax] + [Employers NI] + [Employees NI] AS [Balance]
FROM [Salaries Table];
UNION SELECT ...