I am trying to run two sql queries using sqlalchemy engine in python 3.7. However, I am having trouble joining results columns from two queries. Is there an efficient way to perform this for MSSQL?
Following is the table that is being queried
timestamp startX startY Number
2019-05-13-10:31 695 384 0
2019-05-13-10:32 3914 256 25ZLH3300MEPACC16x25
2019-05-13-10:32 3911 442 25ZLH3300MEPACC16x25
2019-05-13-10:32 3904 2109 25ZLH3300MEPACC16x25
2019-05-13-10:32 3910 627 25ZLH3300MEPACC16x25
2019-05-13-10:32 3904 1445 25ZLH3300MEPACC16x25
and I need to get this as an output
timestamp startX startY Number Quantity
2019-05-13-10:31 695 384 0 1
2019-05-13-10:32 3914 256 25ZLH3300MEPACC16x25 5
First query returns unique records based on Number as follows
SELECT * FROM
(SELECT
[timestamp]
,[startX]
,[startY]
,[Number]
,ROW_NUMBER() OVER(Partition by [Table].Number,
[Table].Number,
type order by [timestamp] DESC) rownumber
FROM [Table]) a WHERE rownumber = 1
Second query returns count of duplicate records as Quantity column with a Number column.
SELECT [Table].Number, count(*) AS 'Quantity'
FROM [Table]
GROUP BY [TABLE].Number
HAVING count(*) >= 1
I would like to join results from query #1 and column quantity from query #2 based on Number as primary key.
connection = engine.connect()
connection.execute(""" Query """)
SELECT * FROM (query1) AS q1 INNER JOIN (query2) AS q2 ON q1.number = q2.number?ORDER BY timestamp DESCwould still give non deterministic (random) results because the timestamps are not unique.. Do you have a column withIDENTITYin your table we need to that to get pure deterministic (fixed) results by adding that also in theORDER BYINNER JOIN, that's caused by havingtypein yourPARTITION BY; in other words, the first query already includes the duplicates that you don't want, so fix the first query.