का उपयोग कर क्वेरी पर SELECT DISTINCT निष्पादित करने के लिए मुझे पिछले 30 दिनों के लिए व्यय अनुमान प्रदर्शित करने की आवश्यकता है। खर्च एक दिन में कई बार गणना की जाती है। यह सरल एसक्यूएल क्वेरी का उपयोग कर प्राप्त किया जा सकता:SQLAlchemy
SELECT DISTINCT ON (date) date(time) AS date, resource_id , time
FROM spend_estimation
WHERE
resource_id = '<id>'
and time > now() - interval '30 days'
ORDER BY date DESC, time DESC;
दुर्भाग्य से मैं एक ही SQLAlchemy का उपयोग कर करने में सक्षम हो नहीं कर पा रहे। यह हमेशा सभी कॉलम पर विशिष्ट चयन बनाता है। जेनरेटेड क्वेरी में distinct on
नहीं है।
query = session.query(
func.date(SpendEstimation.time).label('date'),
SpendEstimation.resource_id,
SpendEstimation.time
).distinct(
'date'
).order_by(
'date',
SpendEstimation.time
)
SELECT DISTINCT
date(time) AS date,
resource_id,
time
FROM spend
ORDER BY date, time
यह ON (date)
सा याद आ रही है। यदि मैं उपयोगकर्ता query.group_by
- तो SQLAlchemy distinct on
जोड़ता है। हालांकि मैं समूह द्वारा उपयोग की गई समस्या के समाधान के बारे में नहीं सोच सकता।
भाग द्वारा अलग-अलग भाग और क्रम में फ़ंक्शन का उपयोग करने का प्रयास किया।
query = session.query(
func.date(SpendEstimation.time).label('date'),
SpendEstimation.resource_id,
SpendEstimation.time
).distinct(
func.date(SpendEstimation.time).label('date')
).order_by(
func.date(SpendEstimation.time).label('date'),
SpendEstimation.time
)
कौन इस एसक्यूएल में हुई:
SELECT DISTINCT
date(time) AS date,
resource_id,
time,
date(time) AS date # only difference
FROM spend
ORDER BY date, time
कौन सा अभी भी DISTINCT ON
याद आ रही है।
आप किस डीबीएमएस का उपयोग कर रहे हैं? AFAIK SQLAlchemy केवल विशिष्ट बोलीभाषाओं पर DISTINCT का समर्थन करता है – architectonic
पुन: @architectonic - http://stackoverflow.com/questions/17223174/returning-distinct-rows-in-sqlalchemy-with-sqlite - पहला उत्तर देखें – Monkpit
पुनः @architectonic अच्छा सवाल - मैं postgresql डेटाबेस का उपयोग कर रहा हूँ। – aisbaa